Reputation: 21
<span class="here one-two-del-del other1">test</span>
<span class="here one-two-aaa o2ther">test</span>
<span class="here one-two-dsf other3">test</span>
<span class="here one-two-213 o4ther">test</span>
<span class="here one-two-sdf other5">test</span>
<span class="here one-two-sdff o6ther">test</span>
<span class="set one-two-aaaa">set 1</span> <br />
<span class="set one-two-bb-fff">set 2</span> <br />
<span class="set one-two-vcvc">set 3</span> <br />
<span class="set one-two-fgdfg-dfgfd-fgf">set 4</span> <br />
$('.set').click(function(){
$('#here').???
})
i would like - if i click on .set then this should get own class and replace in all .here.
For example if i click on set 2 then all span with class .here should be:
<span class="here one-two-bb-fff other1">test</span>
<span class="here one-two-bb-fff o2ther">test</span>
<span class="here one-two-bb-fff other3">test</span>
<span class="here one-two-bb-fff o4ther">test</span>
<span class="here one-two-bb-fff other5">test</span>
<span class="here one-two-bb-fff o6ther">test</span>
i cant use removeClass because i dont know how is the current class. If i use .attr('class', 'new') then this replace all class, but i must still have class other1, o2ther etc
Maybe i must use regular expression?
Upvotes: 0
Views: 165
Reputation: 590
HTML
<span class="here one-two-del-del other1">test</span>
<span class="here one-two-aaa o2ther">test</span>
<span class="here one-two-dsf other3">test</span>
<span class="here one-two-213 o4ther">test</span>
<span class="here one-two-sdf other5">test</span>
<span class="here one-two-sdff o6ther">test</span>
<br />
<span class="set one-two-aaaa">set 1</span> <br />
<span class="set one-two-bb-fff">set 2</span> <br />
<span class="set one-two-vcvc">set 3</span> <br />
<span class="set one-two-fgdfg-dfgfd-fgf">set 4</span>
JavaScript
$('.set').click(function () {
var replaceWith = $(this).attr('class');
// Remove the "set " from replaceWith
replaceWith = replaceWith.replace(/set ?/g, '');
$('.here').each(function () {
var newClass = $(this).attr('class');
newClass = newClass.replace(/one-two-[^ $]+/, '');
newClass = newClass + ' ' + replaceWith;
// Now set the new class
$(this).attr('class', newClass);
});
})
Here's a fiddle: http://jsfiddle.net/NNhDd/3/
Upvotes: 2