0

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);
2
  • 2
    foo is string. Commented Apr 16, 2016 at 15:17
  • You can use regex: foo = foo.replace(/class="(.*?)"/, function(m, $1) { return 'class="' + $1 + ' bar"'; }); Commented Apr 16, 2016 at 15:21

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.