adc90
adc90

Reputation: 303

Iterating through elements returned by jQuery selector

I have some HTML that's structured more or less like which I want to be able to filter though by row.

<div class="parentElement">
   <div class="rowInput">
      <input type="checkbox" />
      <input type="text" value="demo" />
   </div>

   <div class="rowInput">
      <input type="checkbox" />
      <input type="text" value="demo" />
      <select> 
         <option>Value 1</option>
         <option>Value 2</option>
      </select>
   </div>
</div>

I'm able to get the two rows I need with

var row = $('.rowInput');

0: div.row.inputRow
1: div.row.inputRow

However I'm having issues with going through these rows and further and pulling out any information. I've tried a few different methods of looping through the rows however the best I've been able to do is traversing the property list of the elements. What want to do however is go through each element of the div.row.inputRow and pull out the information based on element type so I can store the information by row.

Edit: I was able to get what I wanted with the following code:

for (var i = 0; i < rows.length; i++) {
        console.log(rows[i]);
    for (var j = 0; j < rows[i].childNodes.length; j++) {
            console.log(rows[i].childNodes[j]);
    }
}

However I'm getting errors whenever I try to use the jQuery '.is()' on the child nodes I'm returning

Uncaught TypeError: rows[i].childNodes[j].is is not a function

Basically what I'm going for in the end is returning each element with '.inputRow' so I can filter out the input of each row and either store it or discard it based on if the checkbox is selected. The main reason I'm going this route is I couldn't get the input I needed by row with both a 'select' and ':input' selector.

Upvotes: 1

Views: 214

Answers (2)

mohamed-ibrahim
mohamed-ibrahim

Reputation: 11137

Your code is correct except for the way to get childerens try the following:

var rows = $('.rowInput');

for (var i = 0; i < rows.length; i++) {
  console.log(rows[i]);
  for (var j = 0; j < $(rows[i]).children().length; j++) {
    console.log( $(rows[i]).children()[j]);
  }
}

check it here: jsfiddle

Upvotes: 2

kapantzak
kapantzak

Reputation: 11750

Try each() function:

$('.rowInput').each(function() {
   var $this = $(this);
   var checkbox = $this.find('input[type=checkbox]');
   var text = $this.find('input[type=text]');
});

The $(this) refers to each .rowInput element.

Upvotes: 2

Related Questions