ditto ditto - 10 months ago 20
Javascript Question

Adding a class to an element within a string

I'm wanting to add a class to the form element within the string. Is there an easy way to do this without jQuery?

var foo = '<form class="overlay"><div></div></form>';


The easiest way is to convert foo to a DOM element by using an inmemory div. Then you can convert it back to string with innerHTML after adding the expected class. By the way, it's not recommended to manipulate HTML string with regex or any other string manipulation methods.

var foo = '<form class="overlay"><div></div></form>';
var div = document.createElement('div');
div.innerHTML = foo;