3

http://jsfiddle.net/r4KL9/

This should replace all classes with the corresponding data-change attribute.

So if I had:

<div class="hello" data-change="new-class">

...I would expect it to return

<div class="new-class" data-change="new-class">

My code changes one of them (the one on the button) but not the other.

What am I doing wrong?

Thanks for any help.

--

Apparently I need to post the JS Fiddle code too:

var str = '<div class="original-class" data-change="new-class">Hello</div><div class="class-123"><input type="button" class="start-class" data-change="any-new-class" value="Click Me"></div>';

var html = $('<div/>').html(str).contents();

$('[data-change]', html).attr('class', function() { return $(this).data('change') });

alert( $(html).parent().html() );
0

2 Answers 2

2
var html = $('<div/>').html(str).find('[data-change]').attr('class', function () {
    return $(this).data('change');
}).end().html();

alert(html);

http://jsfiddle.net/n8zMN/

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. If only I could up-vote (and post comments without waiting 15 seconds apart).
1

try this:

$('[data-change]', html).attr('class', function() { return $(this).attr('data-change') });

EDIT:

var html = $(str);
html.filter('[data-change]').attr('class', function() { return $(this).data('change') });

I think it works: http://jsfiddle.net/r4KL9/2/

1 Comment

Thanks, I ended up trying the other answer which worked, but I think yours looks good too.

Your Answer

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.