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?
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?
Share Improve this question edited Dec 29, 2013 at 22:23 Daedalus 7,7225 gold badges38 silver badges63 bronze badges asked Dec 29, 2013 at 22:14 user2023106user2023106 1-
3
.getElementsByTagName()
returns a NodeList – Andreas Commented Dec 29, 2013 at 22:16
3 Answers
Reset to default 2I 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.
You could use .querySelectorAll()
:
https://developer.mozilla/en-US/docs/Web/API/Document.querySelectorAll http://caniuse./queryselector
like so:
var names = document.querySelectorAll('li h2');
which would return a NodeList (https://developer.mozilla/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.