SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Location
    Michigan
    Posts
    38
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question About getElementsByTagName

    Where is the problem in the following code?

    Code:
       totalElementArray = document.getElementsByTagName("li");
       
       j = 0;
       for (i = 0; i < totalElementArray.length; i = i + 1)
       {
          if (totalElementArray[i].getAttribute("id").substr(0, 6) == "liBook")
          {
             elementArray[j] = totalElementArray[i];
             j = j + 1;
          }
       }
    Consider now this alert statement:

    Code:
    alert (elementArray[j].getAttribute("id").substr(0));
    If I put this alert statement after "elementArray[j] = totalElementArray[i];" in the if-statement, it prints out exactly what it should print out.

    However, if I run this for loop:

    Code:
    for (i = 0; i < elementArray.length; i = i + 1)
    alert (elementArray[i].getAttribute("id").substr(0));
    AFTER the end of the previous for loop, NOTHING prints out. What happened to all the items in elementArray?

    Thanks so much.

    Ken

  2. #2
    SitePoint Zealot imouto's Avatar
    Join Date
    Sep 2004
    Location
    Gotham
    Posts
    184
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Would you mind pasting your HTML code as well? Or perhaps put everything up in JS Bin (http://jsbin.com/) and provide your jsbin link.

  3. #3
    SitePoint Zealot imouto's Avatar
    Join Date
    Sep 2004
    Location
    Gotham
    Posts
    184
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I made a local test page and this code seems to give what you're looking for:

    Code:
    <!DOCTYPE html>
    
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Test</title>
    </head>
    
    <body>
    <ul>
      <li id="liBook1">Book One</li>
      <li id="liBook2">Book Two</li>
      <li id="liBook3">Book Three</li>
      <li id="liBook4">Book Four</li>
      <li id="liBook5">Book Five</li>
      <li id="liBook6">Book Six</li>
    </ul>
    <script>
    var totalElementArray = document.getElementsByTagName("li");
    var elementArray = [];
    var i;
    var j = 0;
    
    for (i = 0; i < totalElementArray.length; i++) {
        if (totalElementArray[i].getAttribute("id").substr(0, 6) == "liBook") {
           elementArray[j] = totalElementArray[i];
           console.log(elementArray[j].getAttribute("id").substr(0));
           j = j + 1;
        }
    }
    console.log("elementArray.length outside of first for loop is " + elementArray.length);
    
    for (i = 0; i < elementArray.length; i++) {
      console.log(elementArray[i].getAttribute("id").substr(0));
    }
    
    </script>
    </body>
    </html>
    Using console.log is a much better way to debug JavaScript than using alert. If you're using Firefox and have the Firebug Add-on, open up Firebug and click on the Console tab then refresh your page. Google Chrome, Safari and Opera have a similar built-in developer tool.

  4. #4
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Location
    Michigan
    Posts
    38
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, imouto, for getting back to me. However, I don't understand your answer. I ran the code you wrote. Only the bulleted list shows up. I never used console.log before. Should there have been some output from it like an alert would provide? You use it in three places, and I don't know what it tells me.

    By the way, my Javascript is all in <head></head>, and not following the HTML list. Does this make a difference?

    Bottom line: where is the error in my code?

    Thanks again.

    Ken

  5. #5
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,800
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by kenmorgan View Post
    I never used console.log before. Should there have been some output from it like an alert would provide?
    Yes but you need the console open to see what it writes there (something you ought to have open whenever you are testing JavaScript as all the errors show up there as well).
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  6. #6
    SitePoint Enthusiast
    Join Date
    Jan 2010
    Location
    Michigan
    Posts
    38
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, Stephen. Nice to see you again.

    I did download Firebug, but I'm not even sure whether "console.log" is part of Firebug. Also the Firebug Web site clearly implies a long learning curve, and I'm axious to get a new book review on our Web site. "Alert" also shows the values of any variable at any point, and that would seem to be all we need for the problem I'm having.

    However, another way to do the coding suddenly occurred to me. The new logic works. On the other hand, I surely would appreciate learning why the code in my post #1 doesn't work. I have no doubt that not finding out now what the problem is will come back to haunt me in the future.

    In reviewing this thread, could any of these be the problem or part of it:

    (1) As I said in my post #4, my Javascript code is in <head> rather than following the actual HTML list of book titles.

    (2) document.getElementsByTagName returns a "NodeList," not a true Array variable. Is my code trying to do something only valid on true Arrays?

    (3) This Web page has been working fine as more and more books reviews were added for probably two years now. What caused me to put in this new code that isn't working is that for the first time one of the book reviews on the page (which is below the <li> list of books) has a bulleted list. But only the bulleted list of book titles has an id starting with "liBook"; in fact, the <li>s in the review itself don't have ids at all. So I tried using two arrays, where the second one contained only those <li>s that belonged to the book title list. The <li>s for the book title list all look like this:

    Code:
       <li id="liBookReview1" class="white"
           style="cursor: pointer;">
           <i>The Holy Spirit in the Old Testament</i> by Leon J. Wood (1976)</li>
    One of the later <li>s inside a review looks like this:

    Code:
    <li style="margin-bottom: 15px;">This occasion could not have preceded the Carchemish victory, because the Babylonian king, who at the time laid siege to Jerusalem (Dan. 1:1), had no access as far west as Jerusalem until after this victory had been achieved.</li>
    Could the dissimilarities between the <li>s in the book list and the <li>s within the text of the book review cause a problem with my code posted in my post #1?

    Again, thanks for any help you can give me.

    Ken

  7. #7
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,800
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    All browses have the console built in - all browsers except Firefox also have a JavaScript debugger built in. To access the console in Firefox go into the Tools menu and then select "Web Developer" and then "Web Console".

    The best place to put almost all JavaScript is immediately before the </body> tag - that way you know that all the HTML that the script references is loaded before the script tries to reference it. The only time JavaScript needs to go in the <head> is where the script is potentially redirecting to an different page rather than allowing the current page to load.

    The difference between a nodelist and an array is that a nodelist doesn't have any methods associated with it whereas an array has access to lots of different methods. Your code isn't referencing any array methods so that isn't the cause of any problems.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •