user274926 user274926 - 1 year ago 84
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>'

Answer Source

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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download