开发者

Chain this jquery expression

Is there a way to chain this jQuery expression or improve it? All i really want to do is change "my text" to "new text".

HTML:

<div id="myDiv">
   my text
  <span>button 1</span>
  <span>button 2</span>
</div>

Javascript:

var element = $("#myDiv");
var buttons = 开发者_JAVA技巧element.children().detach();
element.text("new Text");
element.append(buttons);


var element = $("#myDiv");
var buttons = element.children().detach();
element.text("new Text").append(buttons);

Should work fine! You can always chain methods, that use the same selector.


.contents() gets all of the child nodes including text nodes. Get the first node and change the textContent property.

$('#myDiv').contents()[0].textContent = "new text";

if you need to get more complicated you may want to look at Karl Swedberg's Text Children plugin, which provides various different options too.

jQuery is primarily focused on manipulating element nodes (nodeType 1) and not too great a manipulating text nodes outside the context of element nodes. Sometimes the best way is to drop down to "raw JavaScript" :)


No need to bother jQuery at all... plain JavaScript is much quicker for simple tasks as this.

var element =  document.getElementById('myDiv');

element.innerHTML = element.innerHTML.replace('my text','new text');

http://jsfiddle.net/xAhA6/8/


One easy way is to wrap my text with a span. Then you can do $('#myDiv span').first().text('new text');

As for chaining:

This works:

var element = $("#myDiv");
var buttons = element.children().detach();
element.text("new Text").append(buttons);


You can always make a plugin to do what you want:

(function($){
 $.fn.changeText = function(newText) {

    return this.each(function() {
        var element = $(this);
        var divs = element.children().detach();
        element.text(newText).append(divs);
    });
 };
})(jQuery);

//use it like so:
$('#myDiv').changeText('new text');

Then you can chain other methods to that if you want to continue to manipulate $('#myDiv')

Fiddle: http://jsfiddle.net/maniator/DQtjE/


Why not wrap the text in a <p>? Then you would only need:

$("#myDiv p").text("new Text");

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜