lastChild not working

I have the following code:

<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8"/>
<script type = "text/javascript" src = "js/jquery.js" ></script>
</head>
<body>
<div id = 'div'>
    <div id = "1">

    </div>     
    <div id = "2">

    </div>  
</div>         
</body>
</html>

My JavaScript code is:

$(document).ready(function(){
    var lastcommentq   = document.getElementById('div').lastChild.id;
    alert(lastcommentq);
});

It should alert the id of the lastchild of the div with the id 'div' which is '2' but I am getting the alert as "undefined". I don't know what I have done wrong. Please help me.

Answers:

Answer

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.

Answer

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/

Answer

In jquery:

$(function(){
  alert($("#div :last-child").attr('id'));
});
Answer

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.

Answer

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.

Answer

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);
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.