Get list of all input objects using JavaScript, without accessing a form object

前端 未结 3 1270
情歌与酒
情歌与酒 2020-11-29 02:18

I need to get all the input objects and manipulate the onclick param.

The following does the job for links. Looking

相关标签:
3条回答
  • 2020-11-29 02:45

    (See update at end of answer.)

    You can get a NodeList of all of the input elements via getElementsByTagName (DOM specification, MDC, MSDN), then simply loop through it:

    var inputs, index;
    
    inputs = document.getElementsByTagName('input');
    for (index = 0; index < inputs.length; ++index) {
        // deal with inputs[index] element.
    }
    

    There I've used it on the document, which will search the entire document. It also exists on individual elements (DOM specification), allowing you to search only their descendants rather than the whole document, e.g.:

    var container, inputs, index;
    
    // Get the container element
    container = document.getElementById('container');
    
    // Find its child `input` elements
    inputs = container.getElementsByTagName('input');
    for (index = 0; index < inputs.length; ++index) {
        // deal with inputs[index] element.
    }
    

    ...but you've said you don't want to use the parent form, so the first example is more applicable to your question (the second is just there for completeness, in case someone else finding this answer needs to know).


    Update: getElementsByTagName is an absolutely fine way to do the above, but what if you want to do something slightly more complicated, like just finding all of the checkboxes instead of all of the input elements?

    That's where the useful querySelectorAll comes in: It lets us get a list of elements that match any CSS selector we want. So for our checkboxes example:

    var checkboxes = document.querySelectorAll("input[type=checkbox]");
    

    You can also use it at the element level. For instance, if we have a div element in our element variable, we can find all of the spans with the class foo that are inside that div like this:

    var fooSpans = element.querySelectorAll("span.foo");
    

    querySelectorAll and its cousin querySelector (which just finds the first matching element instead of giving you a list) are supported by all modern browsers, and also IE8.

    0 讨论(0)
  • 2020-11-29 02:47
    var inputs = document.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; ++i) {
      // ...
    }
    
    0 讨论(0)
  • 2020-11-29 02:55

    querySelectorAll returns a NodeList which has its own forEach method:

    document.querySelectorAll('input').forEach( input => {
      // ...
    });
    

    getElementsByTagName now returns an HTMLCollection instead of a NodeList. So you would first need to convert it to an array to have access to methods like map and forEach:

    Array.from(document.getElementsByTagName('input')).forEach( input => {
      // ...
    });
    
    0 讨论(0)
提交回复
热议问题