[英]can you use jquery to see if a target contains a <b> tag?
所以,我有这样的事情。
var $list = $("div#item");
我在看:包含在选择器中,但我不确定是否应用于标记或我是否应该执行以下操作:
if($list.find("<b>"))return 1;
else return 0;
推理:为使用内联标记的程序添加功能,并希望维护结构。
目标:if(项目包含内联b,u,i标签)返回1; 否则返回0;
您可以将其简化为单个选择器.find("b,i,u")
并返回布尔比较length > 0
。 如果在#item
中找到任何标签<b><i><u>
,则总长度将> 0
:
return $("#item").find("b,i,u").length > 0;
编辑 :如果你真的想要一个number
零或一个后面而不是boolean
,使用三元组:
return $("#item").find("b,i,u").length > 0 ? 1 : 0;
return document.querySelector("#item b, #item u, #item i") ? 1 : 0;
不需要jQuery。
如果您需要支持IE7及更早版本的浏览器,请尝试以下方法:
var elem = document.getElementById('item');
return elem.getElementsByTagName('b').length
+ elem.getElementsByTagName('i').length
+ elem.getElementsByTagName('u').length == 0 ? 0 : 1;
你也可以用.has()函数做到这一点
我不确定它是最有效的,但我会使用.find
。
function hasInline(targetElement) {
return ($(targetElement).find('b,u,i').length > 0);
}
我还建议扩展该功能,以便您可以指定要检查的内联标签,如下所示:
// 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']);
如果你正在使用jQuery:
var styleElements = $('b,u,i', $list)
采用:
return (styleElements.length) ? 1 : 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.