Home  >  Article  >  Web Front-end  >  The difference between jquery :has() and :contains() selectors

The difference between jquery :has() and :contains() selectors

黄舟
黄舟Original
2017-06-23 11:14:302026browse

jQuery:has() and jQuery:contains() are two similar methods. The difference is:

has is used to judge tags

contains is used to judge text

1. jQuery:has()

<div><p>Hello</p></div>
<div>Hello again!</div>
$("div:has(p)").addClass("test");
//含有p标签的div标签增加test样式

Note: has is in The quotation marks can be included or omitted in the parentheses.

2. jQuery:contains()

<div>John Resig</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>
$("div:contains(&#39;John&#39;)").addClass(&#39;test&#39;);
//给含有John文本的div标签增加test样式

Note: The brackets in contains can contain quotation marks or be omitted.

3. jQuery:empty

<div></div>
<div><span></span></div>
<div>span</div>
$(&#39;div:empty&#39;).addClass(&#39;test&#39;);
//给不含任何文本并且不含任何标签的div增加样式test

According to different content and attributesYou can accurately locate the attributes you need to find

How to filter tags based on content?
:contains Matches elements that contain the given text

$("div:contains(&#39;Jhon&#39;)")

:has Matches elements that contain the element matched by the selector

$("div:has(p)").addClass("test")       p为标签

The above is the detailed content of The difference between jquery :has() and :contains() selectors. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn