Page 1 of 1

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

Posted: 02 Oct 2017, 07:06
by Marius
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?

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

Posted: 02 Oct 2017, 07:11
by 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);