Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use += operator

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


}
like image 323
Misters Avatar asked Jul 10 '26 09:07

Misters


2 Answers

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; 
});
like image 97
Curtis Avatar answered Jul 11 '26 22:07

Curtis


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.

like image 21
Bergi Avatar answered Jul 11 '26 22:07

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!