chaf ch r
chaf ch r

Reputation: 39

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

Upvotes: 2

Views: 89

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206078

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

For multiple images use Element.querySelectorAll():

const data = `<p>
  <img src="nature.png">
  <img src="buildings.png">
</p>`;

const doc = new DOMParser().parseFromString(data, "text/html");
const imgs = doc.querySelectorAll("img");

imgs.forEach(img => {
  console.log(`Found image: ${img.src}`);
});

Upvotes: 2

Related Questions