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
benhowdle89
37.6k74 gold badges208 silver badges342 bronze badges
4 Answers 4
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
Samich
30.4k6 gold badges70 silver badges80 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
benhowdle89
Awesome! I swear i'd seen it written differently before :S
replace() doesn't change the original string, it returns a new one.
answered Oct 10, 2011 at 21:24
Niko
26.8k9 gold badges97 silver badges112 bronze badges
1 Comment
James Johnson
+1 because it's the correct answer, but it would have been even better with an example ;)
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
James Johnson
46.1k8 gold badges75 silver badges111 bronze badges
Comments
Here's a neat way to write it, using the callback version of (削除) basically every jQuery method:attr (削除ここまで)
$(document).ready(function() {
$('.child').attr('rel', function(i, relName) {
$(this).appendTo('#' + relName);
return relName.replace('&','');
});
});
answered Oct 10, 2011 at 21:45
Eric
98.1k54 gold badges257 silver badges389 bronze badges
3 Comments
Bojangles
Very neat indeed. +1 for a novel solution. When you say nearly, what jQuery functions don't have callbacks?
Eric
@JamWaffles: I didn't say "nearly".
Bojangles
You said
basically instead. I just want to know what functions don't have callbacks, or if there's a list of them anywhere.lang-js
&needs to be&in the HTML.