Get first child node of specific type - JavaScript

Viewed 113151

Is it possible to get a child dom element, which will be the first child of a specific type.

For example in both of these examples I want to get the img element:

<a id="mylink" href="#"><img src="myimage.jpg" /></a>

vs.

<a id="mylink" href="#"><span></span><img src="myimage.jpg" /></a>
5 Answers

jQuery killed my vanilla JavaScript! I used to be pretty confident with JS, but now find myself looking up almost everything when I have a project that can't use jQuery.

jQuery (so simple):

$('#mylink').children('img')[0];

Vanilla JS (from yogi's answer above -- thank you):

document.getElementById('mylink').getElementsByTagName('img')[0];
Related