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