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('John')").addClass('test'); //给含有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> $('div:empty').addClass('test'); //给不含任何文本并且不含任何标签的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('Jhon')")
: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!