If you have an HTML string and you want to manipulate it as a real DOM element such as positioning or adding classes to its inner elements, you need to convert that string to a DOM element. I am going to show you how to do that step-by-step.


#1: Implementation

The idea is very straightforward through 3 steps:

  1. Create a wrapper DOM element, which will contain the element you want to get, via the method document.createElement()
  2. Replace the contents of the wrapper element by setting its property innerHTML with the HTML string, then the element you want to get is the first child of the wrapper element
  3. Get that element via the wrapper’s property firstChild

The code looks like this:

const convertStringToDomElement = htmlString => {
  const wrapperElement = document.createElement('div');
  wrapperElement.innerHTML = htmlString;
  const element = wrapperElement.firstChild;
  return element;

#2: Testing

Let’s try.

const element = convertStringToDomElement(
  '<div>Hello <span id="who">World</span>! I am <strong>Vuong Tru</strong>.</div>'

// World

// Vuong Tru

element.querySelector('strong').textContent = 'Vuong B. Tru';
// Vuong B. Tru

// foo bar

#3: Conclusion

As you can see, you can do anything with the converted DOM element even if you do not insert it into the DOM tree of the current document. And yes, you absolutely have the right to do that.