user274926 user274926 - 6 months ago 20
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
<a>
, then make it a string again? Like this

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

Answer

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();
alert(str)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>