views:

205

answers:

6

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
A: 

Wrap this in an if statement and you are good to go

jQuery(jQuery(htmlStr1)).find('img').size() > 0
meosoft
A: 

This will be easier if the strings are in the innerHTML of an element:

function checkIfTagExists(element, tagName) {
    return element.getElementsByTagName(tagName).length > 0;
}

A regex check would probably be insufficient (see http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) :)

If you really do just have the strings, you can create an element from the string, and set the innerHTML to the string, then do the above check on that new element. This is what the $(tagName, htmlContext) would be doing.

Renesis
A: 

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:

var str1ContainsImg = $(htmlStr1 + ":has(img)").length > 1;
var str2ContainsImg = $(htmlStr2 + ":has(img)").length > 1;

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:

var htmlStr3 = "<img src='' />";
var containsEmptyImg = $(htmlStr3 + ":has(img)").length > 1 || 
    $(htmlStr3 + ":has(img)")[0].tagName.toUpperCase() == 'IMG';
rosscj2533
YES! this is exactly what I was looking for :) Thanks!
James Nine
jQuery does some complicated work behind the scenes. Just for reference, if you're implementing a solution like this without the help of jQuery, use the Document Object Model. It gives you an object-oriented interface for doing this, rather than using text manipulations.
Andrew Noyes
This won't work for an XHTML image tag, though: <img ... /> will have length exactly equal to 1.
tvanfosson
@tvanfosson - you're right, I'll edit to include that issue.
rosscj2533
A: 

in straight javascript:

function checkIfTagExists(src, tag) {
    var re = "<"+tag + ">\.+<\\/"+tag+">";
    return new RegExp(re).test(src);
}
Jared
Good solution. But why alert?
David
@david lol sorry, left that in there after testing it :D
Jared
A: 

I would use a speedy RegExp for this, no need to use any jQuery selectors when not needed.

function checkIfTagExists(str, tag) {
    return new RegExp('<'+tag+'[^>]*>','g').test(str);
}
David
A: 

This might have a bit of overhead, but it should be robust enough for use with any given string or the innerHTML of any element.

function getTagCountFromString(string, tag) {
    var count = 0;
    tag = tag.toLowerCase();
    $(string).each(function(idx, el){
        if(el.nodeType === 1) {
           if(el.tagName && el.tagName.toLowerCase() === tag) {
               count++;
           }
           if(el.childNodes.length > 0) {
               try {
                   count += getTagCountFromString(el.innerHTML, tag);        
               } catch (ex) { }
           }
        }
    });
    return count;
}

getTagCountFromString('<img src=""/><a href=""/>', 'img'); //returns 1

Then to get a boolean value you could check if the count is not equal to 0 or make a helper function which does it for you.

illvm