获取特定类型的第一个子节点-JavaScript

有没有可能获得一个子 dom 元素,它将是特定类型的第一个子元素。

例如,在这两个示例中,我都想得到 img元素:

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

对。

<a id="mylink" href="#"><span></span><img src="myimage.jpg" /></a>
116092 次浏览

Try this

var firstIMG = document.getElementById('mylink').getElementsByTagName('img')[0];
var anchor = document.getElementById('mylink');
var images = anchor.getElementsByTagName('img');
var image = images.length ? images[0] : null;

You can also use querySelector:

var firstImg = document.querySelector("#mylink > img:first-of-type");

Here is a javascript function

function getFirst(con,tag)
{
return con.getElementsByTagName(tag)[0];
}




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


//test
var con=document.getElementById('mylink');
var first=getFirst(con,'img');

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];