Reputation: 17
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
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
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
Reputation: 27041
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