How do you make a string in html?

Say you have some HTML that is a string:

let string_of_html = `
  <div>Cool</div>
`;

Maybe it comes from an API or you’ve constructed it yourself from template literals or something.

You can use innerHTML to put that into an element, like:

document.body.innerHTML = string_of_html;

// Append it instead
document.body.innerHTML += string_of_html;

You have a bit more control if you go with the insertAdjacentHTML function as you can place the new HTML in four different places:

<!-- beforebegin -->
<node>
  <!-- afterbegin -->
  text inside node
  <!-- beforeend -->
</node>
<!-- afterend -->

You use it like…

el.insertAdjacentHTML('beforebegin', string_of_html);
el.insertAdjacentHTML('afterbegin', string_of_html);
el.insertAdjacentHTML('beforeend', string_of_html);
el.insertAdjacentHTML('afterend', string_of_html);

There are circumstances where you might want to have the newly-created DOM still in JavaScript before you do anything with it. In that case, you could parse your string first, like:

let dom = new DOMParser()
  .parseFromString(string_of_html, 'text/html');

That will give you a complete DOM, so you’ll then need to yank out the child you added. Assuming it has just one parent element, that’s like…

let dom = new DOMParser()
  .parseFromString(string_of_html, 'text/html');
let new_element = dom.body.firstElementChild;

Now you can mess around with that new_element as needed, I suppose before doing what you need to do with it.

It’s a bit more straightforward to do this though:

let new_element = document.createRange()
  .createContextualFragment(string_of_html);

You’ll get the element directly as a document fragment to append or whatever as needed. This method is notable in that it will actually execute <script>s it finds inside, which can be both useful and dangerous.

There is a considerable amount of nuance to all this. For example, the HTML needs to be valid. Malformed HTML just isn’t going to work. Malformed might also catch you by surprise, like putting a <tr> into a <table> will fail because it’s missing a <tbody>.

Koen Schaft write “Create a DOM node from an HTML string” that covers what we have here but in more detail and with more of the gotchas.


While working with web pages, we often need to convert a string to HTML markup. In this article, you’re going to learn how to convert a piece of text or string to an actual HTML element with JavaScript with examples.

Suppose, you have an HTML string of a <a> tag with the text of About us inside of a <button> tag and you want to convert that string to an HTML document. Like this example-

let ourString = '<button> <a href="#"> About us </a> </button>';

Now, how can we convert this? We’re going to use the DOMParser web API to solve the problem.

What is DOMParser :

The DOMParser interface has the ability to transform XML or HTML source code from a string into a DOM Document. It is a tree-based architecture. Let’s use that.

let ConvertStringToHTML = function (str) {
   let parser = new DOMParser();
   let doc = parser.parseFromString(str, 'text/html');
   return doc.body;
};

In this code, we have created a function expression and defined a function inside of it. The function simply takes a parameter, so that we can pass our declared string which is ‘ourString’. Then we have created an instance of the DOMParser interface and from the object, we called the built-in method parseFromString().

What is parseFromString():

The parseFromString() method of the DOMParser interface converts a string which contains HTML and returns as an HTMLDocument.

The parseFromString() the method takes two parameters. The first one is the string we pass and the second one is the type. In our case, we want to convert to an HTML document, so our type is ‘text/html’. Now, if pass our declared string and log this to our console-

console.log(ConvertStringToHTML(ourString));

OUTPUT:

You can see that the HTML string is converted to an HTML element as a DOM node. Now, you can use the methods of DOM nodes like appendChild() to use the result. The DOMParser also can convert a string to an XML document. We just have to use a different type like ‘text/xml’. So, in this article, you learned how to convert a string to HTML with Javascript. I hope this example will help you. Thank you.

Share on social media

//

PreviousNext

How do you create a string in HTML?

How to Create a New DOM Element from HTML String.
function htmlToElem(html) {.
let temp = document. createElement..
html = html. trim(); // Never return a space text node as a result..
temp. innerHTML = html;.
return temp. ... .
let td = htmlToElem('<td>foo</td>'.
div = htmlToElem('<div><span>nested</span> <span>stuff</span></div>'.

Does HTML have strings?

HTML documents are strings that contain both content and markup. Content looks like: hi there and markup looks like <p> . In HTML they are blended together so that the string <p>hi there</p> tells the browser to display the words hi there to the screen in whatever a paragraph, according to the browser, looks like.

What is meant by string in HTML?

A string can be any text inside double or single quotes: let carName1 = "Volvo XC60"; let carName2 = 'Volvo XC60'; String indexes are zero-based: The first character is in position 0, the second in 1, and so on.

How do I render a string in HTML?

To render the html string in react, we can use the dangerouslySetInnerHTML attribute which is a react version of dom innerHTML property. The term dangerously is used here to notify you that it will be vulnerable to cross-site scripting attacks (XSS).