Reputation: 6277
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);
Upvotes: 0
Views: 35
Reputation: 14866
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);
Upvotes: 1