获取特定类型的第一个子节点 - JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11701118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:46:36 来源:igfitidea点击:
Get first child node of specific type - JavaScript
提问by yogi
Is it possible to get a child dom element, which will be the first child of a specific type.
是否有可能获得一个子 dom 元素,它将是特定类型的第一个子元素。
For example in both of these examples I want to get the img
element:
例如,在这两个示例中,我都想获取img
元素:
<a id="mylink" href="#"><img src="myimage.jpg" /></a>
vs.
对比
<a id="mylink" href="#"><span></span><img src="myimage.jpg" /></a>
回答by yogi
Try this
尝试这个
var firstIMG = document.getElementById('mylink').getElementsByTagName('img')[0];
回答by Zeta
You can also use querySelector
:
您还可以使用querySelector
:
var firstImg = document.querySelector("#mylink > img:first-of-type");
回答by Michael Robinson
var anchor = document.getElementById('mylink');
var images = anchor.getElementsByTagName('img');
var image = images.length ? images[0] : null;
回答by spaceman12
Here is a javascript function
这是一个javascript函数
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');