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") 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?
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. :-)