Reputation: 121
I'm trying to get by jQuery the .attr("msg_g")
of the last-child element
<div id="append">
<div class="h" msg_g="1">A</div>
<div class="y" msg_g="2">B</div>
<div class="h" msg_g="3">C</div>
</div>
I'm pretty sure that script below must work but returns me undefined
var msg_g = $( "#append div:last-child" ).attr( "msg_g" );
console.log(msg_g);
I use the script below for checking if last-child 'hasClass' and works perfect, why doesn't work on .attr()
Example for .hasClass()
if($( "#append div:last-child" ).hasClass( "y" )){
var last_msg_class="by_you";
}else if($( "#append div:last-child" ).hasClass( "h" )){
var last_msg_class="by_friend";
}
Upvotes: 0
Views: 3201
Reputation: 126
I have tested it, and its working. Make sure that your code is executes when DOM element is ready.
$( document ).ready(function() {
var msg_g = $( "#append div:last-child" ).attr( "msg_g" );
alert(msg_g);
});
Check this: http://jsfiddle.net/ytj8z0j7/
Upvotes: 0
Reputation: 25527
Make sure your code runs after dom ready. If your script executes before the rendering of elements, problems will occur.
$(document).ready(function() {
$("#append > div:last").attr("msg_g");
});
Upvotes: 1
Reputation: 18873
Instead of adding msg_g
attribute,try using data-*
attribute.
Modify your html as :--
<div id="append">
<div class="h" data-msg_g="1">A</div>
<div class="y" data-msg_g="2">B</div>
<div class="h" data-msg_g="3">C</div>
</div>
and try this in Jquery :--
var msg_g = $( "#append > div:last" ).data( "msg_g" );
and make sure that you're Jquery code is inside document.ready
block.
Upvotes: 1