I have a variable which stores user html input, this input might be a text or an image. I want to check if the user have entred an image or a simple text
example of user entry
this.userEntries = <p> < img src=" nature.png"></p>
txtOrImg: function () {
// expected logic
if userEntries includes tagname('img') return ... else return ...
}
CodePudding user response:
Use DOMParser() and its parseFromString() Method. Then traverse it using Element.querySelector() to get a desired child Element
const data = `<p><img src="nature.png"></p>`;
const doc = new DOMParser().parseFromString(data, "text/html");
const img = doc.querySelector("img");
if (img) {
console.log("Has image!", img);
} else {
console.log("No image");
}