In Javascript or jQuery, how do I detect if a specific tag exists or not?
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开发者_StackOverflow");
result2 = checkIfTagExists(htmlStr2, "img");
alert(result1); // should output "true" or "1" or whatever
alert(result2); // should output "false" or do nothing
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);
}
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';
Wrap this in an if statement and you are good to go
jQuery(jQuery(htmlStr1)).find('img').size() > 0
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 RegEx match open tags except XHTML self-contained tags) :)
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.
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.
in straight javascript:
function checkIfTagExists(src, tag) {
var re = "<"+tag + ">\.+<\\/"+tag+">";
return new RegExp(re).test(src);
}
精彩评论