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 Get URL Parameters Using jQuery or JavaScript
How to Remove Key from JavaScript Object
How to Attach Event to Dynamic Elements in JavaScript
How to Allow only Alphabet Input in HTML Text Input
How to Remove Empty Element from JS Array
How to Scroll to Bottom of Div
How to Check if String Starts With Another String in JavaScript
How to Call JS Function in IFrame from Parent Page

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