Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select element based on EXACT text contents

Tags:

jquery

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_ads where the index HAS A 1 IN IT, e.g. 1, 10-19, 21, 31, etc.

How can I get ONLY index n?

like image 936
Jason Avatar asked Feb 25 '10 23:02

Jason


People also ask

How do you select an element by its content?

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.

How do I check if a div contains a text?

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.

How use contains in jQuery?

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).

Can we use multiple selectors in jQuery?

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.


1 Answers

How about this:

$('.existing_ad .index').filter(function() {     return $(this).text() == index; }).parents('.existing_ad'); 
like image 55
nickf Avatar answered Oct 06 '22 01:10

nickf