How to use the + = operator
Since I started using JQuery, I've always wondered how this operator works 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 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
}
source to share
You cannot use such shorcuts for jQuery methods, it only works for native assignment operators . For jQuery,.text()
use the callback:
$("#mydiv").text(function(index, oldtext) {
return oldtext + i;
});
This callback function works for all the jQuery "assignment" property, be it .html
, .val
, .prop
, .attr
, .css
, or .text
.
source to share
jQuery is not a programming language, but a library built in javascript, so the rules are exactly the same as the ones you should use using javascript, and javascript is not designed to understand such structures.
Edit
Of course, I mean, that o.m(+1)
does not increase o.p
, but o.p++
and o.p+=1
does:
var o = {};
o.p = 1;
o.m = function () { return this.p; };
o.m(+1); // o.p equals 1
o.p++; // o.p equals 2
o.p+=1; // o.p equals 3
source to share
Like the other answers, jQuery is just a framework and follows the same syntax rules as any JavaScript code.
While I can see the benefit of passing to function
before .text()
, I don't think this is a universal approach for solving your real problem: how to concatenate text when you use a function instead of a variable.
I would rather use Array.join()
for efficient concatenation:
var textParts = [ $("mydiv").text() ];
for(var i = 0;i<=4;i++)
{
textParts[textParts.length] = i;
}
$("mydiv").text(textParts.join(',')) // result: '...,1,2,3,4'
If you prefer a functional looping approach, you can also use Array.map()
.
AFAIK DOM functions are pretty slow, so it is more efficient to do the concatenation first and then set the div
node value .
source to share