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:107
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
Posts:805
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
- Display message to every minute in Javascript
JavaScript - jQuery - Ajax
First post
Hello,
On eatch minute from the current hour I wanna have an message
I can not find out how to complete
I hope to get something like this (code...
Last post
If you only want to display a message to every minute, just use the setInterval() function. It calls a function repeatedly, over and over again, at...
- Hour and Minutes togheter in Javascript
JavaScript - jQuery - Ajax
First post
Dear Coursesweb I can not find out how to add the hours + minutes togheter.
<SCRIPT LANGUAGE= JavaScript >
day = new Date()
hr =...
Last post
See and use the following example:
<script>
var day = new Date();
let hr = day.getHours();
let mn = day.getMinutes();
let se =...