Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Find Label By The Inner Text

I was wondering if it was possible to find a label (or any element, really) by it's inner text. For example:

<label for="myCheckbox">SuperSweetCheckbox</label> 

And I want to find it by the text SuperSweetCheckbox.

I know this seems kind of counter-intuitive, but due to the nature of the app I'm working on it seems to be necessary. I realize that I can iterate through each of the labels but I'd prefer to avoid that option if at all possible.

If anyone could provide some assistance, I'd appreciate it.

like image 632
Chuck Callebs Avatar asked Apr 24 '11 18:04

Chuck Callebs


People also ask

How do I select a span containing a specific text value using jQuery?

To select a span containing a specific text value using jQuery, we can select all the spans and then use the filter method to find the one with the given text value. We call $(“span”) to get all the spans. Then we spread the spans into an array with the spread operator.

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.

What is htmlFor in label?

htmlFor property reflects the value of the for content property. That means that this script-accessible property is used to set and read the value of the content property for , which is the ID of the label's associated control element.


2 Answers

Maybe

$('label[value|="SuperSweetCheckbox"]') 

according to:

http://api.jquery.com/attribute-contains-prefix-selector/

or

$("label:contains('SuperSweet')") 

according to

http://api.jquery.com/contains-selector/

like image 31
Vicente Plata Avatar answered Sep 19 '22 12:09

Vicente Plata


use the selector :contains()

 var element = $("label:contains('SuperSweetCheckbox')"); 

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 bare words or surrounded by quotation marks. The text must have matching case to be selected.

like image 61
Caspar Kleijne Avatar answered Sep 18 '22 12:09

Caspar Kleijne