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
  • 13,333
  • 28
  • 106
  • 203

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
  • 118,038
  • 37
  • 189
  • 297
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
  • 195,511
  • 20
  • 184
  • 225
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,043
  • 1
  • 11
  • 22