Practising with the DOM tree from the Console

Hi everyone,

I’m typing this on the console and using the nav on my website. I copy what it returns. Why is not giving me the nodeValue of the first element in the list (menu)?

document.getElementsByTagName("ul")
[<ul class=​"level_1" role=​"menubar">​<li class=​"sibling first">​…​</li>​<li class=​"sibling">​…​</li>​<li class=​"sibling">​…​</li>​<li class=​"sibling">​…​</li>​<li class=​"sibling">​…​</li>​<li class=​"sibling last">​…​</li>​</ul>​]
var ulList = document.getElementsByTagName("ul");
undefined
ulList.firstChild.nodeValue;
VM2128:2 Uncaught TypeError: Cannot read property 'nodeValue' of undefined(…)

What does it mean undefined here?

Also, can I use className on the console to add a class name like in:

var el = document.getElementsByClassName("one");
undefined
el.className = "two"
"two"

I don’t see the new class added dynamically to the html. Why?

Thanks!

document.getElementsByTagName("ul") returns a HTMLCollection, which doesn’t have a firstChild attribute itself; thus document.getElementsByTagName("ul").fistChild is undefined. You can access specific elements just like the elements of an array; type document.getElementsByTagName("ul")[0].firstChild.nodeValue instead.

Same reason – you’ll have to set the class name of a specific element, not of en entire collection of elements. (Note that you can set className of a collection, hence you’ll get no error message… it just doesn’t have any effect to the DOM.)

thanks! but if I’m not on the console this code works:

var elements = document.getElementsByClassName('hot'); // Find hot items

if (elements.length > 2) {                            // If 3 or more are found

  var el = elements[2];              // Select the third one from the NodeList
  el.className = 'cool';             // Change the value of its class attribute

}

Is it because I’m in the console that I can’t select by class name and set an extra className?

Thanks!

No, it’s working in your code above because you’re setting the className of a specific element, namely document.getElementsByClassName('hot')[2], whereas in your OP you’re setting the className of an HTMLCollection. Have a look here for reference. :-)

great, thanks!

I print the notes and a special request to the team here, would be to have print styles, as there are colored boxes that hide the text.

4 posts were merged into an existing topic: Printing, hides content due to Ad placement

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.