Regular expression getElementById

♀尐吖头ヾ 提交于 2019-11-29 18:13:33

In plain javascript, you could do this generic search which should work in every browser:

var divs = document.getElementsByTagName("div"), item;
for (var i = 0, len = divs.length; i < len; i++) {
    item = divs[i];
    if (item.id && item.id.indexOf("id_123456_") == 0) {
        // item.id starts with id_123456_
    }
}

Working example: http://jsfiddle.net/jfriend00/pYSCq/

This works by recursively traversing the whole DOM.

It's possibly not the most efficient, but should work on every browser.

function find_by_id(el, re, s) {

    s = s || [];
    if (el.tagName === 'DIV' && re.exec(el.id) !== null) {
        s.push(el);
    }

    var c = el.firstChild;
    while (c) {
        find_by_id(c, re, s);
        c = c.nextSibling;
    }

    return s;
}

var d = find_by_id(document.body, /^id_123456_/);

See http://jsfiddle.net/alnitak/fgSph/

Here you are: http://jsfiddle.net/howderek/L4z9Z/

HTML:

<div id="nums">
<div id="id_123456_7890123">Hey</div>
<div id="id_123456_1120092">Hello</div>
<div id="id_555222_1200192">Sup</div>
<div id="id_123456_9882311">Boom</div>
</div>
<br/>
<br/>
<div id="result"></div>​

Javascript:

divs = document.getElementsByTagName("div");
divsWith123456 = new Array();
for (var i = 0;i < divs.length;i++) {
    if (divs[i].id.match("id_123456") != null) {
        divsWith123456.push(divs[i]);
        document.getElementById("result").innerHTML += "Found: divs[" + i + "] id contains id_123456, its content is \"" + divs[i].innerHTML + "\"<br/><br/>";
    }
}​
paje007

HTML DOM querySelectorAll() method will work here.

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

Borrowed from StackOverFlow here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!