Get first child node of specific type - JavaScript

后端 未结 4 1867
刺人心
刺人心 2021-02-04 23:19

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 ele

相关标签:
4条回答
  • 2021-02-04 23:32

    Try this

    var firstIMG = document.getElementById('mylink').getElementsByTagName('img')[0];
    
    0 讨论(0)
  • 2021-02-04 23:33

    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');
    
    0 讨论(0)
  • 2021-02-04 23:41

    You can also use querySelector:

    var firstImg = document.querySelector("#mylink > img:first-of-type");
    
    0 讨论(0)
  • 2021-02-04 23:55
    var anchor = document.getElementById('mylink');
    var images = anchor.getElementsByTagName('img');
    var image = images.length ? images[0] : null;
    
    0 讨论(0)
提交回复
热议问题