ditto ditto - 7 months ago 10
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>';
foo.classList.add('bar');
console.log(foo);

Answer

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;
div.querySelector('form').classList.add('bar');
alert(div.innerHTML);