Search code examples
javascriptfunctionselectelementgetelementsbytagname

Javascript get h2 tag inside li tag and return it


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?


Solution

  • 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.