:contains()
S2C Home « Selectors « :contains()
Containing text selector.
Shorthand version $(':contains(text)')
Description
The :contains()
selector, selects all elements containing the specified text.
The text can appear in the specified element and/or descendants thereof.
If this selector is not preceded by another selector, the universal selector ("*") is implied and so the whole DOM will be searched. Use another selector as in the examples below to narrow the search and improve performance.
Syntax
Signature | Description |
---|---|
jQuery(':contains(text)') | Text match |
Parameters
Parameter | Description |
---|---|
text | The text to search for. |
Return
N/A.
:contains()
ExampleTop
Selects all elements containing the specified text.
The following example will check for the text 'the' in 'p' elements and apply an orange background when the button below is clicked.
$(function(){
$('#btn1').on('click', function() {
$("p:contains('the')").css('backgroundColor', 'orange');
});
});
The following example will check for the text 'only' in 'a' elements and apply a silver background when the button below is clicked (left sidebar and left navigation).
$(function(){
$('#btn2').on('click', function() {
$("a:contains('only')").css('backgroundColor', 'silver');
});
});
The following example will check for the text 'orm' in 'span' elements and apply a cyan background when the button below is clicked (left sidebar and below).
$(function(){
$('#btn3').on('click', function() {
$("span:contains('orm')").css('backgroundColor', 'cyan');
});
});