1

This is the jQuery:

<script type="text/javascript">
 $(document).ready(function(){
 var relName;
 $('.child').each(function() {
 relName = $(this).attr('rel');
 relName.replace('&','');
 $(this).attr('rel', relName);
 $(this).appendTo('#' + $(this).attr('rel'));
 });
 }); 
</script>

With this relevant HTML:

<div rel="MadDogs&EnglishmenHandpaintedfigurines" id="Figurines" class="category section child">
 <h3 class="categoryTitle">Figurines</h3> 
</div>

But for some reason, the replace has no effect whatsoever!

asked Oct 10, 2011 at 21:22
1
  • I'm not sure if this is the whole of your problem, but the & needs to be &amp; in the HTML. Commented Oct 10, 2011 at 21:24

4 Answers 4

8

replace returns string with replaced data. So you need to assign back to your variable.

relName = relName.replace('&','');
answered Oct 10, 2011 at 21:24
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! I swear i'd seen it written differently before :S
3

replace() doesn't change the original string, it returns a new one.

answered Oct 10, 2011 at 21:24

1 Comment

+1 because it's the correct answer, but it would have been even better with an example ;)
2

It's not updating because you're not assigning the result to anything.

Try this instead:

$(this).attr('rel', relName.replace('&',''));
answered Oct 10, 2011 at 21:26

Comments

2

Here's a neat way to write it, using the callback version of (削除) attr (削除ここまで) basically every jQuery method:

$(document).ready(function() {
 $('.child').attr('rel', function(i, relName) {
 $(this).appendTo('#' + relName);
 return relName.replace('&','');
 });
}); 
answered Oct 10, 2011 at 21:45

3 Comments

Very neat indeed. +1 for a novel solution. When you say nearly, what jQuery functions don't have callbacks?
@JamWaffles: I didn't say "nearly".
You said basically instead. I just want to know what functions don't have callbacks, or if there's a list of them anywhere.

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.