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.
CodePudding user response:
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>