skip to Main Content

i have this variable

formEditable = document.getElementById("formid").getElementsByTagName("input");

i want it like that

formEditable = $("#formid").getElementsByTagName("input");

3

Answers


  1. You can use a single selector string instead:

    const inputsInsideForm = $('#formid input');
    

    This will give you a jQuery collection of all input elements which are descendants of the #formid element.

    If you had to use getElementsByTagName instead, extract the element from the $("#formid") collection first:

    $("#formid")[0].getElementsByTagName("input");
    

    This will give you a live HTMLCollection of those inputs.

    Login or Signup to reply.
  2. You Can simply use below code :

    $("#formid").getElementsByTagName("input");
    
    Login or Signup to reply.
  3. In case you have many <input>s in the page, you should use

    // Locate the first element with ID `formid`,
    // then query its descendants for `<input>` elements.
    formEditable = $("#formid").find("input");
    

    for performance reasons since selectors are evaluated right-to-left.

    When using the query $("#formid input"), first all <input>s are located, then they are filtered based on their ancestor elements, looking for an ancestor with ID formid.

    This is nothing unique to jQuery, but your original solution actually takes this into account:

    formEditable = document.getElementById("formid").getElementsByTagName("input");
    

    Note that jQuery queries return a jQuery Object, not a DOMNodeList of elements. So the variable formEditable will be a jQuery Object. To convert a jQuery Object to an array, use the toArray method.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search