5

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

1
  • do you mena something like this $("#parent-id input[type=text]").each(function(){ }); ? Commented Jul 19, 2012 at 10:35

1 Answer 1

10

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") );
});
Sign up to request clarification or add additional context in comments.

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.