JavaScript allows you to select DOM elements in numerous ways using ID, tag, name, class, attributes, etc. Sometimes you may need to select DOM elements based on their HTML text, in JavaScript. In this article, we will learn how to select element by text in JavaScript.
How to Select Element By Text in JavaScript
Let us say you have the following HTML element.
<a ...>SampleText</a>
There are several ways to select element by text in JavaScript.
1. Using XPath
XPath is a simple way to search an element using query selectors.
var xpath = "//a[text()='SampleText']"; var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
2. Using DocumentElement
You can also use outerHTML and innerHTML properties to select DOM elements using HTML text. Here is an example to select elements based on outerHTML attribute.
document.documentElement.outerHTML.includes('SampleText')
Similarly, you can also select DOM elements using innerHTML property.
document.documentElement.innerHTML.includes('SampleText')
3. Using JQuery
JQuery is a powerful and popular JavaScript library that offers many useful functions. You can use the contains() function to easily select DOM elements using their innerHTML text.
var element = $( "a:contains('SampleText')" );
In this article, we have learnt how to select DOM elements using their text values.
Also read:
How to Select Element By Name in JavaScript
How to Get Value of Selected Radio Button
How to Disable Browser AutoFill Using JavaScript
How to Stop Browser Back Button Using JavaScript
How to Disable Clicks in IFrame Using JavaScript
Related posts:
How to Split String With Multiple Delimiters in JS
How to Find DOM Element Using Attribute Value
How to Detect Click Outside Element in JavaScript
How to Check if Web Page is Loaded in IFrame or Web Browser
How to Get Highlighted/Selected Text in JavaScript
How to Add 30 Minutes to JS Date Object
How to Check if Variable is Object in JS
How to Get Previous URL in JavaScript

Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.