lastChild not working

前端 未结 6 789
予麋鹿
予麋鹿 2021-01-25 01:20

I have the following code:







        
相关标签:
6条回答
  • 2021-01-25 01:39

    this is what I would have done, but I'm not clear as to if it's what you want:

    $(function () {
        var lastchild = $('#div div:last-child').attr('id');
        alert(lastchild);
    });
    

    http://jsfiddle.net/pFjPS/

    also, I don't believe classes or ids can start with numbers, so your markup is probably not valid

    edit : HTML5 supports it, but is not generally recommended.

    0 讨论(0)
  • 2021-01-25 01:49

    Your elements probably have text nodes around them, so the last child node of the outer <div> won't necessarily have an "id" attribute.

    I'm not sure if all browsers support it, but there's a "lastElementChild" property that explicitly gets only elements, and not things like comment nodes or text nodes. Failing that, you could just loop through the node list looking for type 1 nodes.

    0 讨论(0)
  • 2021-01-25 01:49

    I would use this approach, since ID is a property and not an attribute.

    $(function () {
        var lastchild = $('#div div:last-child').prop('id');
        alert(lastchild);
    });
    
    0 讨论(0)
  • 2021-01-25 01:50

    In jquery:

    $(function(){
      alert($("#div :last-child").attr('id'));
    });
    
    0 讨论(0)
  • 2021-01-25 01:50

    The jQuery way:

    // assuming the last child is always a div
    var lastcommentq = $('#div > div:last-child').attr('id');
    
    // alternatively
    var lastcommentq0 = $('#div').children('div').last().attr('id');
    

    The JavaScript way:

    var lastcommentq = document.getElementById('div').lastElementChild.id;
    

    Note that this works in all modern browsers and IE 9+. See lastElementChild on MDN.

    0 讨论(0)
  • 2021-01-25 01:52

    is this your wanted behaivour?

    $(document).ready(function(){
         var lastchild   = $("div").last().attr("id")
         alert(lastchild);
         });
    
    
    <div id="div">
        <div id ="1">
    
        </div>     
        <div id="2">
    
        </div>  
    </div>        
    

    check out this fiddle for live example

    http://jsfiddle.net/sHgbF/

    0 讨论(0)
提交回复
热议问题