I have the following code:
<ul class="parentNode" id="parentNode">
<li><span>Inicio</span></li>
<li><span>Categorias</span></li>
<li><span>Contacto</span></li>
</ul>
What JS method could I implement to select only the LIs that are the immediate children but except the SPANs, also when I use the "childNodes" it returns the array: [text, li, text, li, text, li, text] , sorry the question but what does the element at position 0 (text) correspond to? that is, according to me there should be 3 text, but there are 4.
One last question, when I try to select the UL with "getElementsByClassName" it doesn't work and it returns "Undefined" but when I use "getElementById" it works correctly, why does that happen?
var listItems = document.getElementById('parentNode').childNodes; //Funciona, devuelve "NodeList(7) [text, li, text, li, text, li, text]"
var ListItems = document.getElementsByClassName('parentNode').childNodes; //No Funciona, devuelve "undefined"
you can try with this
This will get all
li
inside the element with the id parentNode. UsequerySelector
to get elements using CSS selectors, this only returns the first element with the selector; to get all elements usequerySelectorAll
From what I understood in your question, you are not understanding the order of the nodes, being
span
a child node andli
the parent and child node at the same timeul
, it willli
return the label withspan
it since it is a child node.Edit
Regarding your question (already edited)
getElementsByClassName
it does not return an element, but rather an array and you will have to specify the position of the element to just be able to execute a function or obtain a propertyyou could use
Node.children
Example: