Reputation:
How can I use second/third div in JS/JQuery without using class or id on this element?
<div class="parentcontainer">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
And also is there any possibility to find out what child element by number(order) it is? Like:
<div class="parentcontainer">
<div class="hey"></div>
<div class="hey"></div>
<div class="hey"></div>
<div class="hey"></div>
</div>
$('.hey').click(function(){
// what element by number is that?
});
Upvotes: 1
Views: 76
Reputation: 189
// return position
$('.parentcontainer').on('click', '.hey', function(){
alert($(this).index());
});
// select nth with eq
$('.parentcontainer').find('.hey').eq(2).css('background', 'red');
Upvotes: 0
Reputation: 30607
Use :eq()
var secondInnerDiv = $('div div:eq(1)');
var thirdInnerDiv = $('div div:eq(2)');
$('div div:eq(1), div div:eq(2)').css('background', 'green');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="parentcontainer">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
Or :lt()/gt()
var secondAndThirdInnerDiv = $('div div:gt(0):lt(2)');
$('div div:gt(0):lt(2)').css('background', 'green');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="parentcontainer">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
Update
Use index()
$(this).index()
$('div div').click(function(){
console.log($(this).index());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="parentcontainer">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
Upvotes: 1
Reputation: 14454
You can use the slice() method:
var secondAndThirdDiv = $("div div").slice(1,3);
You basically specify the range of elements you want (0
index based of course).
Upvotes: 0
Reputation: 2574
Here is the code that gives a hint on one of the approaches
var allDivs = $(".parentcontainer > div");
var secondDiv = $(allDivs.get(1));
var thirdDiv = $(allDivs.get(2));
Upvotes: 0
Reputation: 8386
This is what I'd use for example:
div > div:first-child {
background-color:yellow;
}
Note that div > div
selects all the immediate div childrens. For the demo I made it highlight only the first child using :first-child
Upvotes: 0
Reputation: 134
you can work with this I quess:
https://api.jquery.com/nth-child-selector/
Upvotes: 0