How to make out of a HTML string a JavaScript DOM object

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 62

How to make out of a HTML string a JavaScript DOM object

Hello,
How can I create a JavaScript DOM object out of string with HTML content?
For example, i have this string which i get with ajax from database:

Code: Select all

var str ='abc 123<div id="test">coursesweb.net</div><span class="cls">some text</span>';
What would be the right way to create a JavaScript DOM object out of that string?

Admin
Hello,
You can use DOMParser() to create a #document from a string:

Code: Select all

var str ='abc 123<div id="test">coursesweb.net</div><span class="cls">some text</span>';

const parser = new DOMParser();
const doc_str = parser.parseFromString(str, 'text/html');//get the html string as a js object

var ob_test = doc_str.getElementById('test');
alert(ob_test.innerHTML);

Or, another method, you can add the string into a hidden Div in page, then get with javascript the elements you want from that Div. Like in this code:

Code: Select all

var str ='abc 123<div id="test">coursesweb.net</div><span class="cls">some text</span>';
document.querySelector('body').insertAdjacentHTML('beforeend', '<div id="doc_str" style="display:none;">'+str+'</div>');
var doc_str = document.getElementById('doc_str'); //get the added html string as a js object
var ob_test = doc_str.querySelector('#test'); //object with #test element
alert(ob_test.innerHTML);

Similar Topics