Since I started using JQuery ive always wondering how does this operator work in JQuery Example:
for(var i = 0;i<=4;i++)
{
document.getElementById("mydiv").innerText += i;//<- works as expected
}
//results will be 0,1,2,3,4
but if i use JQuery instead i dont know how to do it
for(var i = 0;i<=4;i++)
{
$("mydiv").text(+i)//<- NO!
$("mydiv").text+(i)//<- NO!
$("mydiv").+text(i)//<- JAJA COME ON!
$("mydiv").text(i)+//<- I guess that was stupid
}
This isn't possible like this. Unlike innerText, text() is a method, not a property.
Try:
$("mydiv").text($("mydiv").text() + i);
Or if you'd rather not make 2 references to $("mydiv") you can do:
$("mydiv").text(function(i,v){
return v + i;
});
You can't use such shorcuts for jQuery methods, it only works for native assignment operators. For jQuery .text(), use a callback:
$("#mydiv").text(function(index, oldtext) {
return oldtext + i;
});
This callback thing works for all jQuery property "assignments", be it .html, .val, .prop, .attr, .css, or .text.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With