0

Any ideas why this jquery is not working?

$("div.aboutText p a").each( function() {
 $(this).replace(' ', 'ert');
});

OK... so I have a link that looks something like this...

<a href="#">My Link</a>

And I want it to look something like this...

<a href="#">MyertLink</a>
asked Jan 12, 2011 at 9:37
1
  • replace can not be run on a jQuery object. What do you want to do? Commented Jan 12, 2011 at 9:40

6 Answers 6

3

.replace() is a string method - it won't work on a jQuery object. Try:

$(this).text($(this).text().replace(" ", "ert"))
answered Jan 12, 2011 at 9:40
Sign up to request clarification or add additional context in comments.

1 Comment

$(this).text($(this).text().replace(/ /gi, 'ert')); - this replaces every occurrence of a space. Thanks!
1

When you want to replace something in the text of the a tag use this:

$("div.aboutText p a").each( function() {
 $(this).text($(this).text().replace('/ /', 'ert'));
});
answered Jan 12, 2011 at 9:41

Comments

1

.replace() is a plain Javascript method, it's not encapsulated by jQuery. So I guess you want to replace either the text() or the href value from your anchors.

$("div.aboutText p a").each( function() {
 $(this).text(function(i, text) {
 return text.replace(' ', 'ert');
 });
});

or

$("div.aboutText p a").each( function() {
 $(this).attr('href', (function(i, href) {
 return href.replace(' ', 'ert');
 });
});
answered Jan 12, 2011 at 9:41

Comments

1

You should replace text or html:

$(this).html($(this).html().replace(" ", "ert"));

Or:

$(this).text($(this).text().replace(" ", "ert"));

To actually replace all instances of space, you will have to use regex with /g modifier like this:

$(this).text($(this).text().replace(/' '/g, 'ert'));

Another method would be using split and join like this:

$(this).text($(this).text().split(' ').join('ert'));
answered Jan 12, 2011 at 9:40

1 Comment

I'm pretty sure .text() returns by value, so this won't actually set the text
0
answered Jan 12, 2011 at 9:41

Comments

0

What you want might be this instead:

$("div.aboutText p a").each(function() {
 var t = $(this).text().replace(" ","ert");
 $(this).text(t);
});

$(this) will return the a tag, but what part of the A tag are you trying to replace? the text?

answered Jan 12, 2011 at 9:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.