3

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


}
Ron
  • 22,128
  • 31
  • 108
  • 206
Misters
  • 1,337
  • 2
  • 16
  • 29

5 Answers5

3

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; 
});
Curtis
  • 101,612
  • 66
  • 270
  • 352
1

You just need to work with jQuery here. Use the text method to extract the value, and then call it again to set the new value:

for(var i = 0;i<=4;i++)
{
    var mydiv = $("mydiv"),
        t = mydiv.text();
    mydiv.text(t + i);
}
Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
1

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

jQuery is not a programming language but a library built upon javascript, so, the rules are exactly the same as those you have to follow using javascript, and javascript has not been designed to understand these kinds of structures.


Edit

Of course I mean o.m(+1) does not increment o.p while 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
0

Like other answers point out, jQuery is just a framework and is subject to same syntactic rules as any JavaScript code.

While I see the advantage of passing in a function to .text(), I don't think it's a general purpose approach to solve your real problem : how to concatenate text when you use a function instead of a variable.

I'd favor the usage of 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 the function approach over a loop, you could also use Array.map().

AFAIK DOM functions are rather slow so it's more effective to do the concatenation first and then set the div node value.

Antoine Lassauzay
  • 1,557
  • 11
  • 12