Get element by part of Name or ID

后端 未结 2 1421
抹茶落季
抹茶落季 2020-11-28 12:51

Here is an example of my form (only inputs that I want, but there is many others):

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 13:05

    Your best bet is probably document.querySelectorAll, which you can use any CSS selector with, including an "attribute starts with" selector like input[id^="id_qtedje_"]. It's supported on all modern browsers, and also IE8:

    var elements = document.querySelectorAll('input[id^="id_qtedje_"]');
    

    If you wanted just the first match (rather than a list), you could use document.querySelector instead. It returns a reference to the first match in document order, or null if nothing matched.

    Alternately, you could give the elements a class name, then use document.getElementsByClassName, but note that while getElementsByClassName was supported in old versions of Chrome and Firefox, IE8 doesn't have it, so it's not as well-supported as the more-useful querySelectorAll in the modern era.

    var elements = document.getElementsByClassName("theClassName");
    

    If you use any libraries (jQuery, MooTools, Closure, Prototype, etc.), they're likely to have a function you can use to look up elements by just about any CSS selector, filling the gaps in browser support with their own code. For instance, in jQuery, it's the $ (jQuery) function; in MooTools and Prototype, it's $$.

提交回复
热议问题