Regular expression getElementById

前端 未结 4 1884
别跟我提以往
别跟我提以往 2020-12-21 19:04

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 n

4条回答
  •  一整个雨季
    2020-12-21 19:28

    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/

提交回复
热议问题