Samridhi Sinha
Samridhi Sinha

Reputation: 17

Iterate through mutiple div using jquery

I have a model something

<div id="item">
  <div id ="subitem">
    <div id="first"></div>
    <div id="two"></div>
  </div>
</div>

How can I access all the div inside the subitem and every div has different set of operations. Sorry I am new to this.

Upvotes: 0

Views: 61

Answers (3)

Raeesh Alam
Raeesh Alam

Reputation: 3480

You need to use .each() method with help of > Child Selector and * Asterisk operator.

Like:
element > * = Selects all div elements where the parent is a #subitem element.

Useful Links:
Combinators: https://www.w3schools.com/css/css_combinators.asp
Each Method: https://api.jquery.com/each/

$(document).ready(function () {
    $('#subitem > *').each(function(i,v) {
        console.log($(this).text())
    });   
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="item">
    <div id="subitem">
        <div id="first">First</div>
        <div id="two">Second</div>
        <div id="three">Third : <span>Sub-child</span></div>
    </div>
</div>

Upvotes: 0

Rahul Kumar
Rahul Kumar

Reputation: 3157

Use children() method to get the children of element filtered by optional selector "div" and iterate over the matched DOM elements using each() method.

$("#subitem").children("div").each(function () {
    console.log(this.id, this.textContent);
});
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div id="item">
  <div id ="subitem">
    <div id="first">abc data</div>
    <div id="two">xyz data</div>
  </div>
</div>
<body>
<html>

Upvotes: 1

You can use .each() and depending on what operations you want to run you can for example use if and if else statements.

$("#subitem > div").each(function() {
  if (this.id == "first") {
    console.log("found div with id " + this.id)
  } else if (this.id == "two") {
    console.log("found div with id " + this.id + ", and it's the second div")
  }
});

Demo

$("#subitem > div").each(function() {
  if (this.id == "first") {
    console.log("found div with id " + this.id)
  } else if (this.id == "two") {
    console.log("found div with id " + this.id + ", and it's the second div")
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="item">
  <div id="subitem">
    <div id="first"></div>
    <div id="two"></div>
  </div>
</div>

Upvotes: 2

Related Questions