你可以使用jquery来查看目标是否包含<b>标签吗?</b>

时间:2012-08-21 16:52:35

标签: javascript jquery

所以,我有类似的东西。

 var $list = $("div#item");

我在看:在选择器中包含,但我不确定是否应用于标记或者我应该做类似的事情:

 if($list.find("<b>"))return 1;
 else return 0;

推理:为使用内联标记的程序添加功能,并希望维护结构。

目标:if(项目包含内联b,u,i标签)返回1;否则返回0;

6 个答案:

答案 0 :(得分:8)

您可以将其简化为单个选择器.find("b,i,u")并返回布尔比较length > 0。如果在<b><i><u>中找到任何标记#item,则总长度将为> 0

return $("#item").find("b,i,u").length > 0;

Proof of concept

修改:如果您确实需要number零或一个代替boolean,请使用三元组:

return $("#item").find("b,i,u").length > 0 ? 1 : 0;

答案 1 :(得分:5)

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;

答案 2 :(得分:4)

也许使用.has()方法。

$('li').has('ul')

jquery has

答案 3 :(得分:3)

你也可以用.has()函数

来做到这一点

答案 4 :(得分:0)

我不确定它是最有效的,但我会使用.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']);

答案 5 :(得分:0)

如果你正在使用jQuery:

var styleElements = $('b,u,i', $list)

使用:

return (styleElements.length) ? 1 : 0;
相关问题