5

Environment: Just JavaScript

Is there a way to get an element that contains partial text?

<h1 id="test_123_abc">hello world</h1>

In this example, can I get the element if all I had was the test_123 part?

Rod
  • 14,529
  • 31
  • 118
  • 230

3 Answers3

5

Since you can't use Jquery, querySelectorAll is a descent way to go

var matchedEle = document.querySelectorAll("[id*='test_123']")
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
5

querySelectorAll with starts with

var elems = document.querySelectorAll("[id^='test_123']")
console.log(elems.length);
<h1 id="test_123_abc">hello world</h1>
<h1 id="test_123_def">hello world</h1>
<h1 id="test_123_ghi">hello world</h1>
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

You can achieve it (without using jQuery) by using querySelectorAll.

var el = document.querySelectorAll("[id*='test_123']");

You can get a clear example of it by going through the following link:
Find all elements whose id begins with a common string

haMzox
  • 2,073
  • 1
  • 12
  • 25