Given the following strings:
htmlStr1 = "<img>test1</img>";
htmlStr2 = "<div>test2</div>";
I’d like to know if there’s a way to write a function just to detect for the “img” tag (for example). So if both of these strings are passed to it, and it should not do anything if the 2nd string is passed to it.
so for example, you’d run a function like:
result1 = checkIfTagExists(htmlStr1, "img");
result2 = checkIfTagExists(htmlStr2, "img");
alert(result1); // should output "true" or "1" or whatever
alert(result2); // should output "false" or do nothing
If this is more of an example of functionality you are looking for and not the exact situation you’d use it in, the jQuery has selector may be helpful.
Related question with example.
For this situation you would do:
Edit: As tvanfosson pointed out in the comments, if your img tag doesn’t have a closing tag (
<img src='' />),this exact solution wouldn’t work. If that’s an issue, you can check the tag name of the first element returned like this: