user274926
user274926

Reputation: 28

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>'

Upvotes: 1

Views: 214

Answers (2)

Satpal
Satpal

Reputation: 133403

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>

Upvotes: 5

papersnake
papersnake

Reputation: 205

if you use jquery you can use 'addClass'

js
$("a").addClass("foo");

Upvotes: -2

Related Questions