Regular expression getElementById

2020-02-16 04:09发布

I need to use pure Javascript for the first time in a long while, and having gotten used to the comfy mattress of jQuery, all the important stuff is escaping me.

I need to select a bunch of divs on regular expression. So I have stuff like this;

<div id="id_123456_7890123"> .. </div>
<div id="id_123456_1120092"> .. </div>
<div id="id_555222_1200192"> .. </div>
<div id="id_123456_9882311"> .. </div>

And I'd need to create a loop that goes through all the divs with an id that begins with id_123456_. How would I go about doing that?

I used jQuery with the :regex filter plugin before, but looking at it, it doesn't seem like there's much I could salvage in a pure javascript rewrite.

4条回答
虎瘦雄心在
2楼-- · 2020-02-16 04:33

HTML DOM querySelectorAll() method will work here.

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

Borrowed from StackOverFlow here

查看更多
劳资没心,怎么记你
3楼-- · 2020-02-16 04:47

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/

查看更多
▲ chillily
4楼-- · 2020-02-16 04:49

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/

查看更多
疯言疯语
5楼-- · 2020-02-16 04:54

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/>";
    }
}​
查看更多
登录 后发表回答