Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Separating HTML tags from a javascript string into individual strings

I have Javascript string which is

 "<div>" +
 "<h2>What color does the blackcurrant berry actually have?</h2>" +
 "<img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600">" +
 "<audio><source src="horse.ogg" type="audio/ogg"></audio>" +
 "</div>"

and the expected result is three separate strings. like

expected output:

console.log(title) // "<h2>What color does the blackcurrant berry actually have?</h2>"
console.log(image) // "<img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600">"

Please help with how to do this. Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I would render the JS string into HTML, then access it’s children.

document.getElementsByTagName("body")[0].innerHTML = "<div>" +
 "<h2>What color does the blackcurrant berry actually have?</h2>" +
 "<img src=`img_girl.jpg` alt='Girl in a jacket' width=`500` height=`600`>" +
 "<audio><source src=`horse.ogg` type='audio/ogg'></audio>" +
 "</div>"

let title = document.getElementsByTagName("body")[0].children[0].children[0]

let image = document.getElementsByTagName("body")[0].children[0].children[1]

console.log(title)
console.log(image)
<body></body>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading