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

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

黄舟
Release: 2017-06-23 11:14:30
Original
2056 people have browsed it

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样式
Copy after login

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样式
Copy after login

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
Copy after login

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;)")
Copy after login

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

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template