Jquery Each Input Within DIV (Has A Table)

17,772

This below will find all inputs inside the div element. It will then leave a log of the id of this element.

$("div > input").each(function() {
  console.log( $(this).attr("id") );
});

if you need the div id containing the inputs you could use .parent()

$("input").each(function() {
  console.log( $(this).parent().attr("id") );
});
Share:
17,772
Lemex
Author by

Lemex

Updated on June 28, 2022

Comments

  • Lemex
    Lemex almost 2 years

    Im currently trying to get all input elements from a DIV.

    $("[required]").each(function() {
    
    });
    

    I have this code which returns every element with a required attribute.

    I know within the function of that each() I can use each item like:

    $(this)
    

    So I get the div ID's shown below, and try to get all the inputs from it via:

    var id = $(this).attr('id');
    console.log("### " + id);
    console.log($("#" + id + " > :input").length);
    

    Which returns 0 when I have 4 in put elements within that DIV (also theres a table in the div).

    What I would ideally like to do is for each input element within my div, print its ID.

    UPDATED

    <div id="contactAddress" required="true">
    
     <td>Addres line 1:</td>
     <td colspan="2">
     <input type="text"/>
     </td>
     <td>Addres line 2:</td>
     <td colspan="2">
     <input type="text" />
     </td>
     </tr>
    </div>
    
    console.log($(this).html());
    

    Shows nothign but if i add anythign outsire the or like below...

     <div id="contactAddress" required="true">
     <input type="text" />
    

    And run console.log($(this).html()); It shows it put not the table?

    Any ideas im using Jquery Mobile

  • Lemex
    Lemex almost 12 years
    Yes but for either the div ID or the this (being the div element)
  • Undefined
    Undefined almost 12 years
    $(this) refers to each input as it goes through each. You need the id of the div?
  • Lemex
    Lemex almost 12 years
    var id = $(element).attr('id'); $("#" + id + " > input")