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";
}
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments