admin管理员组文章数量:1302957
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;
本文标签: javascriptcan you use jquery to see if a target contains a ltbgt tagStack Overflow
版权声明:本文标题:javascript - can you use jquery to see if a target contains a <b> tag? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741729925a2394793.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论