简体   繁体   中英

can you use jquery to see if a target contains a <b> tag?

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;

You can simplify it down to a single selector .find("b,i,u") and return the boolean comparison 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

你也可以用.has()函数做到这一点

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 recommend 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM