Question

I want to obtain a h2 tag inside an li tag with javascript, not jquery. Currently this is the html:

<li vriend="Alvin Heijmans" select="">
     <img class="portret" src="img/alvin.png" />
     <div class="addbutton"></div>
     <h2>Alvin Heijmans</h2>
     <p>Utrecht</p>
</li>

Now I want to select the h2 tag inside the li using the following javascript:

var elms = document.getElementsByTagName('li');
var names = elms.getElementsByTagName('h2');

The console is giving the following error:

TypeError: elms.getElementsByTagName is not a function
var names = elms.getElementsByTagName('h2');

So how can this be solved?

Was it helpful?

Solution 3

You could use .querySelectorAll():

https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll http://caniuse.com/queryselector

like so:

var names = document.querySelectorAll('li h2');

which would return a NodeList (https://developer.mozilla.org/en-US/docs/Web/API/NodeList) containing all elements matching the CSS selector: li h2.

Or, if you're just looking for a single element, you could just use .querySelector() which would return a reference to the first element matching your selector.

OTHER TIPS

I believe getElementsByTagName will return an array. so for the second call you'll need to write:

var names = elms[0].getElementsByTagName('h2');

To access the first found li

Edit2:

You need to use this (looped through a for() to capture all of the li and h2 on the page):

var elms = document.getElementsByTagName('li'),
    names = [];
for (var i = 0, j = elms.length; i<j; i++) {
    names = elms[i].getElementsByTagName('h2');
}
alert(names[0].innerHTML);

JSFiddle (has alert instead of log)

Explained:

Your first line assigns a node list (represented inside of an array) with all of the <li> elements inside, represented by a number (starting at 0 for the first one, of course).

The second line does the same, so accessing it requires that you specify the individual node to use

Therefore, you append [0] to access first (in this case, only) h2 inside of the [0] (first/only) li on the page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top