ditto ditto - 2 years ago 69
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>';

Answer Source

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;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download