Can anyone tell me if it’s possible to find an element based on its content rather than by an ID or class?
I am attempting to find elements that don’t have distinct classes or IDs. (Then I then need to find that element’s parent.)
isherwood
57.6k16 gold badges113 silver badges154 bronze badges
asked Sep 6, 2011 at 14:54
2
You can use the :contains
selector to get elements based on their content.
Demo here
$('div:contains("test")').css('background-color', 'red');
<div>This is a test</div>
<div>Another Div</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
answered Sep 6, 2011 at 14:58
gen_Ericgen_Eric
222k41 gold badges297 silver badges337 bronze badges
9
In jQuery documentation it says:
The matching text can appear directly within the selected element, in
any of that element’s descendants, or a combination
Therefore it is not enough that you use :contains()
selector, you also need to check if the text you search for is the direct content of the element you are targeting for, something like that:
function findElementByText(text) {
var jSpot = $("b:contains(" + text + ")")
.filter(function() { return $(this).children().length === 0;})
.parent(); // because you asked the parent of that element
return jSpot;
}
informatik01
16k10 gold badges72 silver badges104 bronze badges
answered Apr 1, 2014 at 6:39
yoav barneayoav barnea
5,7922 gold badges22 silver badges27 bronze badges
1
Fellas, I know this is old but hey I’ve this solution which I think works better than all. First and foremost overcomes the Case Sensitivity that the jquery :contains() is shipped with:
var text = "text";
var search = $( "ul li label" ).filter( function ()
{
return $( this ).text().toLowerCase().indexOf( text.toLowerCase() ) >= 0;
}).first(); // Returns the first element that matches the text. You can return the last one with .last()
Hope someone in the near future finds it helpful.
answered Mar 17, 2016 at 7:52
MorgsMorgs
1,5463 gold badges19 silver badges34 bronze badges
0
Rocket’s answer doesn’t work.
<div>hhhhhh
<div>This is a test</div>
<div>Another Div</div>
</div>
I simply modified his DEMO here and you can see the root DOM is selected.
$('div:contains("test"):last').css('background-color', 'red');
add «:last» selector in the code to fix this.
albert
8,1143 gold badges46 silver badges63 bronze badges
answered May 17, 2015 at 18:26
Terry LinTerry Lin
2,50021 silver badges20 bronze badges
1
The following jQuery selects div nodes that contain text but have no children, which are the leaf nodes of the DOM tree.
$('div:contains("test"):not(:has(*))').css('background-color', 'red');
<div>div1
<div>This is a test, nested in div1</div>
<div>Nested in div1<div>
</div>
<div>div2 test
<div>This is another test, nested in div2</div>
<div>Nested in div2</div>
</div>
<div>
div3
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
answered Oct 8, 2019 at 20:55
Nicholas SushkinNicholas Sushkin
12.9k3 gold badges29 silver badges20 bronze badges
2
Best way in my opinion.
$.fn.findByContentText = function (text) {
return $(this).contents().filter(function () {
return $(this).text().trim() == text.trim();
});
};
answered Nov 3, 2015 at 19:19
rplaurindorplaurindo
1,23714 silver badges23 bronze badges
Yes, use the jQuery contains
selector.
answered Sep 6, 2011 at 14:55
Alex TurpinAlex Turpin
46.6k23 gold badges113 silver badges145 bronze badges
2
All answers so far do not match all specific elements containing a direct child text node which contains a specific text.
Consider the following example. We want to find all hobbits, that is, all div
s containing a direct child text node, which contains the word «hobbit» (including word borders, ignoring the case).
$(function() {
const ELEMTYPE = Node.ELEMENT_NODE
const TEXTTYPE = Node.TEXT_NODE
/*
Behaves a bit like Python's os.walk().
The `topdown` parameter is not strictly necessary for this example.
*/
function* walk_text(root, topdown=true) {
const childs = []
const textchilds = []
for (const child of root.childNodes) {
const childtype = child.nodeType
if (childtype === ELEMTYPE) {
childs.push(child)
} else if (childtype === TEXTTYPE) {
textchilds.push(child)
}
}
if (topdown) {
yield [root, textchilds]
}
for (const child of childs) {
yield* walk_text(child, topdown)
}
if (!topdown) {
yield [root, textchilds]
}
}
function* walk_matching(startnode, nodepat, textpat) {
for ( [elem, textchilds] of walk_text(startnode) ) {
if ( nodepat.test(elem.nodeName) ) {
for ( const textchild of textchilds ) {
if ( textpat.test(textchild.nodeValue) ) {
yield elem
break
}
}
}
}
}
// raw dom node
let startnode = $('body')[0]
// search for element nodes with names matching this pattern ...
let nodepat = /^div$/i
// ... containing direct child text nodes matching this pattern
let textpat = /bhobbitb/i
for ( const node of walk_matching( startnode, nodepat, textpat ) ) {
$(node).css({
border: '1px solid black',
color: 'black'
})
}
});
div {
margin:10px 0;
padding: 10px;
border: 1px solid silver;
color: silver;
font-style:italic;
}
div:before {
display:block;
content: attr(name);
font-style:normal;
}
/* Inserted by SO, we are not interested in it */
body + div {
display: none;
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Find the hobbits</title>
</head>
<body>
<div name='Tolkien'>
book writer
<div name='Elrond'>
elven king
<div name='Arwen'>elven princess</div>
<div name='Aragorn'>human king, son-in-law</div>
</div>
<div name='Gandalf'>
wizard, expert for hobbits
<div name='Bilbo'>
old hobbit
<div name='Frodo'>
young hobbit
<div name='Samweis'>best friend hobbit</div>
</div>
</div>
<div name='Gollum'>ex hobbit</div>
<div name='Odo'>hobbit</div>
</div>
</div>
<script src= "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>
</html>
The other answers find (when searching for ‘hobbit’):
- Rocket Hazmat’s answer: Tolkien, Gandalf, Bilbo, Frodo, Samweis, Gollum, Odo
- Morgs’s answer: Tolkien
- yoav barnea’s answer: Gandalf, Frodo
- Nicholas Sushkin’s answer: Samweis, Gollum, Odo
- Rocket Hazmat’s answer in the comments, Terry Lin’s answer, rplaurindo’s answer: Odo
All of these answers make sense, depending on what you want to do. Choose wise, because Rocket Hazmat’s answers, Morgs’s answer and Terry Lin’s answer partially perform more than two times faster than my solution. I guess that is because they don’t need to walk through the whole DOM. Most answers who use .filter()
perform very fast.
answered Mar 24, 2021 at 5:13
Nils LindemannNils Lindemann
1,0371 gold badge15 silver badges25 bronze badges
contains selector
Description: Select all elements that contain the specified text.
-
version added: 1.1.4jQuery( «:contains(text)» )
text: A string of text to look for. It’s case sensitive.
The matching text can appear directly within the selected element, in any of that element’s descendants, or a combination thereof. As with attribute value selectors, text inside the parentheses of :contains()
can be written as a bare word or surrounded by quotation marks. The text must have matching case to be selected.
Example:
Finds all divs containing «John» and underlines them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Demo:
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
We will learn how to find an element using jQuery’s API. This article requires some knowledge of HTML, CSS, JavaScript, Bootstrap, and jQuery. The elements can be selected based on whether they contain the string we want to find. This can be done using the jQuery contains selector to select elements that contain the string.
About contains selector
Depending on the element, the matching text can appear directly within or within a descendant of the selected element. The :contains() selector in jQuery is used to select elements containing the specified string. The text must have a matching case to be selected.
Syntax: A string of text to look for. It’s case-sensitive.
jQuery(":contains(text)")
Approach:
- Create an HTML file “index.html” in your local system.
- Follow the basic HTML template and two-paragraph by adding the text inside the <p> tag.
- Select the <p> tag with contains selector and pass the keyword that you want to select as a parameter in contains selector method.
- After you successfully follow the above steps then attach a CSS property to that selected paragraph which contains the keyword that you pass as an argument in the contains method.
Example: In this case, we are looking for the element that contains the word “Gfg”. We change the color of the particular paragraph that contains the word “Gfg” after selecting the element.
HTML
<!DOCTYPE html>
<
html
>
<
head
>
<
link
href
=
rel
=
"stylesheet"
integrity
=
"sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin
=
"anonymous"
>
<
script
src
=
</
script
>
<
style
>
body {
border: 2px solid green;
min-height: 240px;
}
.center {
display: flex;
justify-content: center;
}
h1 {
color: green;
text-align: center;
}
</
style
>
</
head
>
<
body
>
<
h1
>GeeksforGeeks</
h1
>
<
div
class
=
"row container"
>
<
div
class
=
"col"
>
<
p
>
Web development refers to the building,
creating, and maintaining of websites.
Gfg includes aspects such as web design,
web publishing, web programming, and
database management. It is the creation
of an application that works over the
internet i.e. websites.
</
p
>
</
div
>
<
div
class
=
"col"
>
<
p
>
Web development refers to the building,
creating, and maintaining of websites.
It includes aspects such as web design,
web publishing, web programming, and
database management. It is the creation
of an application that works over the
internet i.e. websites.
</
p
>
</
div
>
</
div
>
<
script
>
$('p:contains("Gfg")').css({ 'color': 'green' });
</
script
>
</
body
>
</
html
>
Output:
contains text
Last Updated :
01 Oct, 2021
Like Article
Save Article
The :contains() is a jQuery selector that allows us to search text within the element and select it and perform an action on it.
For example – you are dynamically listing records from the MySQL database table here, you have a requirement to add a search filter based on keypress. In case you can use jQuery AJAX which requests and load data from the server every time when the user press key in the search field.
You can simplify this with :contains() jQuery selector to filter data on the Client side.
There are some other ways in jQuery by which you can do the same operation. But, in this tutorial, I explain how you can use :contains() selector for search text.
Note – The :contains() by default performs case-sensitive search. In the example, I show how you can use for case-sensitive and case-insensitive search.
Contents
- :contains()
- Layout
- Search Text in Container
- With specific class in Container
- Case-insensitive
- Conclusion
It selects the element which contains the specified value.
Syntax –
$( ":contains( 'search text' )" );
Example
$( "div:contains( 'hello' )" )
2. Layout
I have created post list where the input field is for search text and the <div class='content'>
element which contains <div class='title'>
and a <p>
element.
Completed Code
<div class='container'> <!-- Search control --> <div> <input type='text' id='search' placeholder='Search Text'> </div> <!-- Content list --> <div class='content'> <div class='title'> <a href='https://makitweb.com/dynamically-add-and-remove-element-with-jquery/' > Dynamically add and remove element with jQuery </a> </div> <p>In this post, I show how you can add and remove new element within your web page with jQuery...</p> </div> <div class='content'> <div class='title'> <a href='https://makitweb.com/how-to-delete-value-from-array-in-javascript/'> How to Delete a value from an Array in JavaScript </a> </div> <p>There are many cases when we have to remove some unused values from the Array which no longer needed within the program...</p> </div> <div class='content'> <div class='title'><a href='https://makitweb.com/read-and-get-parameters-from-url-with-javascript/'>Read and Get Parameters from URL with JavaScript</a></div> <p>If you are familiar with PHP where for reading parameters from URL you can use either $_GET or $_REQUEST which take the name of the argument and return value of it...</p> </div> <div class='content'> <div class='title'> <a href='https://makitweb.com/html-how-to-show-text-above-image-on-hover/'> HTML – How to Show Text Above Image on Hover </a> </div> <p>In this quick tutorial, I show How you can show text above Image when the user hovers the image using only HTML and CSS, no jQuery and JavaScript...</p> </div> </div>
3. Search Text in Container
The first start with a basic example, where I search input text within the <div class='content'>
container if the text is available then show otherwise hide containers.
Completed Code
$(document).ready(function(){ $('#search').keyup(function(){ // Search text var text = $(this).val(); // Hide all content class element $('.content').hide(); // Search and show $('.content:contains("'+text+'")').show(); }); });
View Demo
4. With specific element in Container
Now search for child elements with the specific class.
Completed Code
$(document).ready(function(){ $('#search').keyup(function(){ // Search text var text = $(this).val(); // Hide all content class element $('.content').hide(); // Search $('.content .title:contains("'+text+'")').closest('.content').show(); }); });
The above code searches the input value in title class if it finds then show the parent container.
View Demo
5. Case-insensitive
# Example 1
$(document).ready(function(){ $('#search').keyup(function(){ // Search text var text = $(this).val(); // Hide all content class element $('.content').hide(); // Search $('.content .title:contains("'+text+'")').closest('.content').show(); }); }); $.expr[":"].contains = $.expr.createPseudo(function(arg) { return function( elem ) { return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; }; });
# Example 2
Loop all .content
class and search text with indexOf()
.
$(document).ready(function(){ $('#search').keyup(function(){ // Search text var text = $(this).val().toLowerCase(); // Hide all content class element $('.content').hide(); // Search $('.content .title').each(function(){ if($(this).text().toLowerCase().indexOf(""+text+"") != -1 ){ $(this).closest('.content').show(); } }); }); });
Both give the same output –
View Demo
6. Conclusion
This makes your selection process little easier if you are searching for value in the element and want to take action on it like – update CSS style, add or remove CSS class, remove elements.
If you found this tutorial helpful then don’t forget to share.
Последнее обновление Сен 22, 2021
При создании сайтов а именно при написании скриптов веб разработчики часто сталкиваются с необходимостью найти определенный текст, а если быть точнее то найти блок с определенным текстом. В данном примере мы разберем как именно можно найти блок с текстом и произвести с ним определенные манипуляции.
Задача
Необходимо найти блок с текстом “featured”и удалить span блок который следует за родительским элементом нашего блока (с текстом). Затем удалить сам блок с текстом.
JS готовый скрипт
jQuery(document).ready(function($){
$('span.tg-cats-holder').each(function(){
$(this).find('span.tg-item-term:contains("featured")').closest('a.product_visibility').next('span:contains(",")').remove();
$(this).find('span.tg-item-term:contains("featured")').closest('a.product_visibility').remove();
});
});
Описание логики скрипта
Для решения данной задачи перебираем каждый (ну в данном примере я так решил) родительский блок в котором находятся все наши блоки с которыми необходимо произвести все манипуляции – в моем примере это блок “span.tg-cats-holder”. Перебор мы производим при помощи .each.
$('span.tg-cats-holder').each(function(){
Далее в функции ищем наш блок с текстом, за содержащийся в блоке текст отвечает:
После того как блок с текстом был найден переходим к родительскому блоку при помощи .closest:
.closest('a.product_visibility')
После перехода, находим находящийся рядом с родительским блоком span содержащий “|” и удаляем его:
.next('span:contains("|")').remove();
Далее, при помощи .remove() происходит удаление и самого блока.
Пример на CodePen.io
Источник записи: