Find div in html with javascript and regex

I am trying to select an html element with javascript without! JQuery ...

for example my html:

<div id="my1231">
</div>

and I want to select any first div with id started with my, and I will try:

var regex = /my(.*)/; 
var templateCode = document.match(regex)
alert(templateCode);

but nothing happened, what am I doing wrong? how to select a div with regex, where the first part of id is static and the second is random?

+3
source share
3 answers

If you really want to use the regex to match identifiers, you must first get a list of nodes and then skip it and check each identifier separately. Then you can add each corresponding element to a new array:

var divs = document.getElementsByTagName('div');
var regex = /my(.*)/, matches = [];

for(i=0; i< divs.length; i++){
    if(regex.test(divs[i].id)){
        matches.push(divs[i]);  
    }
}

Jsfiddle

+2
source

How about document.querySelectorAll?

document.querySelectorAll("[id^='my']")

>= IE8

http://caniuse.com/#search=querySelectorAll

+6

Of course, you can always mix both answers and use function detection to determine which method to use:

var divs;
var matches = [];
var re = /^my\w+/;

if (document.querySelectorAll) {
  matches = document.querySelectorAll("[id^='my']");

} else if (document.getElementsByTagName) {
  divs = document.getElementsByTagName('div');

  for(i=0, iLen=divs.length; i<iLen; i++){

    if (re.test(divs[i].id)) {
      matches.push(divs[i]);  
    }
  }
}

NTN.

+1
source

All Articles