user274926 user274926 - 11 months ago 47
jQuery Question

Add class to element in a string

I have this string

var string = 'this is a string <a href="/bar">this is a element</a>';

How can I add a class foo to de element
, then make it a string again? Like this

'this is a string <a href="/bar" class="foo">this is a element</a>'


Create DOM element using the HTML string, manipulate and get the required string.

var str = 'this is a string <a href="/bar">this is a element</a>'
str = $('<div></div>').html(str).find('a').addClass('myClass').end().html();
<script src=""></script>