so, i have something like this.
var $list = $("div#item");
I was looking at :contains in the selector, but i wasnt sure if that applied to markup or if i should do something like:
if($list.find("<b>"))return 1;
else return 0;
Reasoning: Adding functionality to a program which uses inline tags, and want to maintain structure.
Goal: if(item contains an inline b, u, i tags) return 1; else return 0;
so, i have something like this.
var $list = $("div#item");
I was looking at :contains in the selector, but i wasnt sure if that applied to markup or if i should do something like:
if($list.find("<b>"))return 1;
else return 0;
Reasoning: Adding functionality to a program which uses inline tags, and want to maintain structure.
Goal: if(item contains an inline b, u, i tags) return 1; else return 0;
Share Improve this question edited Aug 21, 2012 at 16:53 Fallenreaper asked Aug 21, 2012 at 16:52 FallenreaperFallenreaper 10.7k15 gold badges75 silver badges139 bronze badges6 Answers
Reset to default 8You can simplify it down to a single selector .find("b,i,u")
and return the boolean parison length > 0
. If any of the tags <b><i><u>
are found inside #item
, the overall length will be > 0
:
return $("#item").find("b,i,u").length > 0;
Proof of concept
Edit: If you really want a number
zero or one back instead of the boolean
, use a ternary:
return $("#item").find("b,i,u").length > 0 ? 1 : 0;
return document.querySelector("#item b, #item u, #item i") ? 1 : 0;
No need for jQuery.
If you need to support browsers IE7 and older, try this:
var elem = document.getElementById('item');
return elem.getElementsByTagName('b').length
+ elem.getElementsByTagName('i').length
+ elem.getElementsByTagName('u').length == 0 ? 0 : 1;
perhaps use the .has()
method.
$('li').has('ul')
jquery has
you can also do that with .has() function
I'm not sure it's the most efficient, but I would use .find
for this.
function hasInline(targetElement) {
return ($(targetElement).find('b,u,i').length > 0);
}
I'd also remend expanding the function so you could specify whatever inline tags you wanted to check, like so:
// NOTE: This will return true if the element has ANY of the tags provided.
function hasInlineTags(targetElement, listOfTags) {
return ($(targetElement).find(listOfTags.join(',')).length > 0);
}
// Call it with whatever tags you want.
hasInlineTags($("div#item"), ['b','u','i']);
if you're using jQuery:
var styleElements = $('b,u,i', $list)
Use:
return (styleElements.length) ? 1 : 0;