开发者

How can I use += with jQuery selectors easier?

I've taken the following example from JS Bin:

HTML

<p id='js'>Hello, World!</p>`

JavaScript

document.getElementById('js').innerHTML += ' – this was inserted using JavaScript';`

Now, I'd like to do the same with jQuery. Since I couldn't find a way to use += with jQuery selectors (otherwise I wouldn't ask this question), here is the开发者_C百科 long way:

var js = $('#js').html() + ' – this was inserted using JavaScript';
$('#js').html(js);

I use jQuery because it's syntax is shorter and simpler. But these two codes have almost the same length.

This does not work:

$('#js').innerHTML += ' – this was inserted using JavaScript';


With jQuery, you can use append instead.

Your $('#js').innerHTML += ' – this was inserted using JavaScript'; would work with a [0], though, e.g.:

$('#js')[0].innerHTML += ' – this was inserted using JavaScript';
//      ^^^--- here

...because you can access the raw DOM element that way. But it's a bad idea to append content via innerHTML because it makes the browser work really hard: First it has to loop through its internal DOM equivalent, serializing it into an HTML string, then it has to re-interpret the new HTML after you've done your +=. (Granted the latter will be really, really fast because rendering HTML into their internal structures is what browsers do and they're highly optimized for it, but the former may not be fast at all.)


$('#js').append(' – this was inserted using JavaScript');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜