tags:

views:

38

answers:

3

Is there a way to tell jQuery that you want what ever comes after text() or html() to be applied to it? Hard to explain, easier to show:

$("#someElement").html().replace(oldWord, newWord, "g");

The above won't change the DOM, you'd have to do:

$("#someElement").html($("#someElement").html().replace(oldWord, newWord, "g"));

which is a pain in the a**.

edit: What I'd like to see though, is the possiblity to do this:

$("#someElement").html(.replace(oldWord, newWord("g"));

Don't know if that would be possible, or even practical, really. Is there a reason this couldn't be done?

A: 

No, you get the HTML code as a string, and you have to put the string back after changing it.

For a construction like that to work, the html function would have to return an object that had methods like replace that you could use to alter the content. However, that would not be efficient if you wanted to apply more than one change (which is pretty much the point of chaining methods), as it would have to get the HTML code and put it back for each change. When you get the HTML code as a string you can do whatever you like with it, and put it back when you are done with it.

Guffa
+2  A: 

No those functions return strings, not jQuery. You first need to get the value, perform your magic, then set the value back. You'd have to do this with plain javascript as well, but the syntax might not be as bothersome.

 var elem = $("#someElement").get(0);
 elem.innerHTML = elem.innerHTML.replace(oldWord,newWord,"g");

Personally, I'd stick with jQuery, but separate it to make it more readable.

 var elem = $("#someElement");
 var html = elem.html();
 elem.html( html.replace(oldWord,newWord,"g") );
tvanfosson
+2  A: 

You could make this into a simple plugin really easily:

jQuery.fn.replaceHTML = function (old, new) {
    return this.each(function() {
        var $t = $(this);
        $t.html($t.html().replace(old, new);
    });
};

// usage:
$('#myElement').replaceHTML('foo', 'bar');
$('#anotherElement').replaceHTML(/f(?:oo|u)/g, 'bar');

This won't break your chaining either:

$('#blah').replaceHTML('abc', 'def').hide();

As Doug D commented, just remember that regexes + html can be unpredictable and could cause problems unless you are very careful.

nickf