How to convert HTML string into DOM elements?

0 votes

Is there a way to convert HTML like:

<div>
<a href="#"></a>
<span></span>
</div>

or any other HTML string into DOM element? (So that I could use appendChild()). I know that I can do .innerHTML and .innerText, but that is not what I want -- I literally want to be capable of converting a dynamic HTML string into a DOM element so that I could pass it in a .appendChild().

Oct 8 in Java-Script by kartik
• 35,820 points
102 views

1 answer to this question.

0 votes

Hello @kartik,

You can use a DOMParser, like so:

var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";
var doc = new DOMParser().parseFromString(xmlString, "text/xml");
console.log(doc.firstChild.innerHTML); // => <a href="#">Link...
console.log(doc.firstChild.firstChild.innerHTML); // => Link

Hope it works!!

Thank you!!

answered Oct 8 by Niroj
• 78,120 points

Related Questions In Java-Script

0 votes
1 answer

How to create HTML elements using jQuery?

Hello @kartik,  if you're doing $('<div>'), jQuery will also ...READ MORE

answered Sep 18 in Java-Script by Niroj
• 78,120 points
33 views
0 votes
1 answer

How to remove all child elements of a DOM node in JavaScript?

Hello @kartik, Use modern Javascript, with remove! const parent = ...READ MORE

answered Sep 21 in Java-Script by Niroj
• 78,120 points
139 views
0 votes
1 answer

How do I turn a string to a json in Node.js?

Hello Kartik, Use the JSON function  JSON.parse(theString) ...READ MORE

answered Apr 24 in Java-Script by Niroj
• 78,120 points
104 views
0 votes
1 answer
+1 vote
1 answer

How to make anchor tag with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

answered Mar 18 in Laravel by Niroj
• 78,120 points
3,506 views
0 votes
1 answer

What is redirection in Laravel?

Named route is used to give specific ...READ MORE

answered Mar 18 in Laravel by Niroj
• 78,120 points
418 views
0 votes
1 answer

How to install Laravel via composer?

Hello, This is simple you just need to ...READ MORE

answered Mar 23 in Laravel by Niroj
• 78,120 points
287 views
+1 vote
1 answer

What are named routes in Laravel and How can specify route names for controller actions?

Hey @kartik, Named routing is another amazing feature of ...READ MORE

answered Mar 23 in Laravel by Niroj
• 78,120 points
4,204 views
0 votes
1 answer

How to convert entire div data into image and save it into directory without using canvas?

Hello @kartik, You can try the sample code ...READ MORE

answered Apr 29 in Java-Script by Niroj
• 78,120 points
9,373 views
0 votes
1 answer

How to convert HTML to JSON using PHP?

Hello @kartik, If you are able to obtain ...READ MORE

answered Jun 19 in Java-Script by Niroj
• 78,120 points
1,164 views