I have a list of divs that all contain a p
tag classed as index
. The textual content of these p
tags is a number from 1 to n (although probably no more than maybe 30-40). I had the following selector, which worked fine in preliminary testing:
var ad = $('.existing_ad .index:contains('+index+')').parents('.existing_ad');
Where index
is the numeric index I retrieved from the p
tag and .existing_ad
is the class of the parent div
. As I said, this worked fine... until I went with higher numbers. For instance, when the index is 1, it selects the .existing_ad
s where the index HAS A 1 IN IT, e.g. 1, 10-19, 21, 31, etc.
How can I get ONLY index n?
To find elements by content:Use the document. querySelectorAll method to select DOM elements by tag. Use the for...of loop to iterate over the collection. On each iteration, check if the textContent of the element matches the expected content.
To check if a div element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.
The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).
You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.
How about this:
$('.existing_ad .index').filter(function() { return $(this).text() == index; }).parents('.existing_ad');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With