Chuck Callebs Chuck Callebs - 6 months ago 96
jQuery Question

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.

Answer

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.