Verify whether a variable includes the tag name "img."

Currently, I am working with a variable that holds user input in HTML format. This input may consist of either plain text or an image. I am looking to determine whether the user has entered an image or just simple text.

Here is an example of user entry:

this.userEntries = <p> < img  src=" nature.png"></p>

txtOrImg: function () {
// The logic we are aiming for 
if the userEntries contain the tag name 'img', then return ... otherwise, return ...
}

Answer №1

Utilize the DOMParser() method along with its parseFromString() Method. Afterwards, navigate through it using Element.querySelector() to access a specific child Element

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

const documentParsed = new DOMParser().parseFromString(content, "text/html");
const imageElement = documentParsed.querySelector("img");

if (imageElement) {
  console.log("Image found!", imageElement);
} else {
  console.log("No image found");
}

To handle multiple images, utilize Element.querySelectorAll():

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

const documentParsed = new DOMParser().parseFromString(content, "text/html");
const allImages = documentParsed.querySelectorAll("img");

allImages.forEach(image => {
  console.log(`Image found: ${image.src}`);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to prevent excessive rerenders when verifying if database information has been successfully retrieved?

Hey there, I'm encountering an issue where the if statement check in my code is causing a "too many rerenders" problem. I'm trying to create a delay between pulling data from the database and calculating the BMI. Any suggestions on how to resolve ...

How to Store Values from a ReadStream in an Array

I'm currently attempting to use a stream and the async/await keywords with the fast-csv library in order to read a CSV file synchronously. Unfortunately, the function I've written doesn't seem to be producing the expected output. My assumpt ...

Utilizing ReactJS to fetch data from Material-UI's <TableRow/> component upon selection - a comprehensive guide

I've integrated Material-UI's <Table/> (http://www.material-ui.com/#/components/table) component with <TableRow/> containing checkboxes in a ReactJS project. While I can successfully select rows by checking the boxes, I am struggling ...

Develop a responsive image component with flexible dimensions in React

I am currently working on developing a dynamic image component that utilizes the material-ui CardMedia and is configured to accept specific height and width parameters. The code snippet I have is as follows: interface ImageDim extends StyledProps { wid ...

Enhancing error handling with Axios in Vue.js

I'm facing an issue with global error handling in axios while making calls in Vue.js. Despite trying various methods, such as triggering user logout, the code block after the axios call still gets executed when an error occurs. Is there a way to preve ...

elevate the div with a floating effect

My goal is to create a chat feature for users that will only be visible for a limited time period. I was thinking of using PHP and timestamp to achieve this functionality, but I also want to make the chat visually disappear by having the message div float ...

The use of set.has in filtering does not produce the desired outcome

I am attempting to use Set.has to filter an array in the following way: const input = [ { nick: 'Some name', x: 19, y: 24, grp: 4, id: '19340' }, { nick: 'Some name', x: 20, y: 27, grp: 11, id: '19343' }, { ...

Invoke a function from a page that has been reloaded using Ajax

After making an Ajax request to reload a page, I need to trigger a JavaScript function on the main page based on certain database conditions. This is necessary because I require some variables from the main page for the function. PHP code: if($reset_regi ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

Having trouble with JQuery toggle()? Need some assistance with fixing it?

My attempts to utilize JQuery toggle functionality have been unsuccessful. The sliding up and down animation is not smooth and instead happens very quickly. I aim to achieve a sliding effect in my code similar to this example (Please refer to Website Des ...

Is it possible to pass slot data back to the parent component in Vue in order to propagate a prop down?

Within my parent component, I am using a MyGrid component to display data. Inside MyGrid, I have logic that checks the type of each item and applies a class called typeSquare if it meets certain criteria. To maintain the simplicity and "dumbness" of MyGr ...

Resolving Typescript custom path problem: module missing

While working on my TypeScript project with Express.js, I decided to customize the paths in my express tsconfig.json file. I followed this setup: https://i.stack.imgur.com/zhRpk.png Next, I proceeded to import my files using absolute custom paths without ...

What methods does Angular use to display custom HTML tags in IE9/10 without causing any issues for the browser?

Exploring web components and utilizing customElements.define tends to cause issues in IE9/10. I've noticed that Angular is compatible with IE9/10, and upon inspecting the DOM tree, it seems like Angular successfully displays the custom element tags. ...

"Effortlessly move elements with HTML5 drag and drop functionality from either direction

I'm working on an application that requires Html5 Drag and Drop functionality, which is currently functioning well. However, in the app, there may be instances where a dropped item is no longer needed and I want to allow users to re-drag and drop it b ...

Laravel route does not receive a parameter sent via Ajax

I am currently using Laravel 5.8 and implementing a discount code system on my website. To achieve this, I attempted to send data via Ajax in the following manner: $.ajax({ type: 'POST', url: baseurl + 'discount/register', ...

modifying variable values does not impact what is displayed on the screen

I'm currently facing an issue with AngularJS. I have two HTML blocks within an ng-repeat and I need to display one of them at each step. <div class="col-md-3" style="margin-top:80px" ng-init="checkFunction()"> <div id="left_group_stage"& ...

Enhance the functionality of a form by dynamically adding or deleting input rows using

The feature for adding and deleting input rows dynamically seems to be experiencing some issues. While the rows are successfully created using the add function, they are not being deleted properly. It appears that the delete function call is not function ...

I am facing difficulties in adding dynamic content to my JSON file

I've encountered a challenge in appending new dynamic data to a JSON file. In my project, I receive the projectName from an input form on the /new page. My API utilizes node.js's fs module to generate a new JSON file, where I can subsequently add ...

Developing a personalized Magento2 extension with added support for PWA technologies

Greetings, fellow developers! I find myself at a crossroads when it comes to PWA and custom Magento 2 extensions. As a backend developer for Magento, my knowledge of PWA frontend implementation is lacking. Currently, I am in the process of developing an SE ...

Deciding on the proper character formatting for each individual character within the RICHT TEXT EDITOR

After browsing numerous topics on Stackoverflow, I was able to develop my own compact rich text editor. However, one issue I encountered is that when the mouse cursor hovers over already bold or styled text, it's difficult for me to identify the styl ...