tags:

views:

29

answers:

2

I cannot upgrade my jQuery, and I was wondering why this function is not existing. How can I implement this:

$('#block-block-1 .content').replace(/^\s*|\s*$/g,'');

What I get is: "function doesn't exist"

thanks

+2  A: 

If I'm reading this right, you want to change the text of that particular element. You can do this using the .text method. We use element.text() to retrive the text and element.text(newText) to set it. We can combine both to alter it.

var content = $('#block-block-1 .content');
content.text(content.text().replace(/^\s*|\s*$/g,''));

If you want to work with multiple elements, you can use the .each method to operate on each one separately.

$('#block-block-1 .content').each(function(content) {
    content.text(content.text().replace(/^\s*|\s*$/g,''));
});
Samir Talwar
+1  A: 

.replace() is a member of JavaScript's string object, not a jQuery object. Therefore, you need to get the text of the jQuery object, change it, and update the jQuery object:

var content = $('#block-block-1 .content');
var text = content.text();
var replacedText = text.replace(/^\s*|\s*$/g,'');
content.text(replacedText);

Or, using text(function(index, text)), a better way:

$('#block-block-1 .content').text(function(index, text) {
    return text.replace(/^\s*|\s*$/g,'');
});

EDIT:

Darn, the second one's jQuery 1.4 only.

Eric
Didn't know you could use a function in `text`. I'll be remembering that.
Samir Talwar
As of 1.4, you can use a function for pretty much everything.
Eric