Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find div in html with javascript and regex

I try to select html element with javascript without! jQuery...

for example my html is:

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

and i want to select any first div with id started with my, and i try so:

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

but nothing happend, what i do wrong? how to select div with regex, where first part of id is static, and second random?

like image 987
byCoder Avatar asked Dec 09 '25 22:12

byCoder


2 Answers

How about document.querySelectorAll?

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

Just be aware of the >= IE8 support

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

like image 145
Sgoldy Avatar answered Dec 11 '25 11:12

Sgoldy


If you really want to use regex to match against ids, you must first get a node list and then loop through it and check each id individually. You can then append each matching 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

like image 29
George Avatar answered Dec 11 '25 10:12

George



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!