3

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
  • 12,599
  • 23
  • 97
  • 188

3 Answers3

2

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

var matchedEle = document.querySelectorAll("[id*='test_123']")
Suresh Atta
  • 114,879
  • 36
  • 179
  • 284
2

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
  • 185,306
  • 18
  • 175
  • 214
0

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
  • 1,923
  • 1
  • 9
  • 20