Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class to first child using javascript

Tags:

javascript

is there any reason this chain does not work? It does not add the class:

document.getElementsByTagName('nav')[0].firstChild.className = "current"

It should return the first child of the nav element which is an <a> which does not happen.

Thanks for your help!

like image 394
cmplieger Avatar asked Sep 11 '12 01:09

cmplieger


People also ask

Can you add a class in JavaScript?

The class name attribute can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name. Adding the class name by using JavaScript can be done in many ways. Using . className property: This property is used to add a class name to the selected element.

How do you append a class in JavaScript?

var element = document. getElementById(element_id); element. className += " " + newClassName; Voilà.


2 Answers

That's because you have text nodes between nav and a. You can filter them by nodeType:

var childNodes = document.getElementsByTagName('nav')[0].childNodes;
for (var i = 0; i < childNodes.length; i++) {
    if (childNodes[i].nodeType !== 3) { // nodeType 3 is a text node
      childNodes[i].className = "current";  // <a>
      break;
    }        
}

It may seem strange but, for example, if you have the following markup:

<nav>
<a>afsa</a>
</nav>

Here's a DEMO.

Why does this happen? Because some browsers may interpret the space between <nav> and <a> as an extra text node. Thus, firstChild will no longer work since it'll return the text node instead.

If you had the following markup, it'd work:

<nav><a>afsa</a></nav>
like image 103
João Silva Avatar answered Oct 25 '22 23:10

João Silva


You can simply document.querySelectorAll to select the list. use "firstElementChild" to get first child node and add class.

 const firstChild = document.querySelectorAll('nav').firstElementChild;
 firstChild.classList.add('current');
like image 23
Vikas Gupta Avatar answered Oct 25 '22 23:10

Vikas Gupta