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

check if a variable contains img tagname

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 ...
}

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 :

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");
}
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