Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if element is last or first child of parent in javascript/jquery?

I have the following code, emulating a click on the left or right key down events. This is used as part of a gallery slideshow:

$(document).keydown(function (e) {
                    if(e.keyCode == 37) { // left
                        $(".thumb-selected").prev().trigger('click');
                    }
                    else if(e.keyCode == 39) { // right
                        $("thumb-selected").next().trigger('click');
                    }
                });

Essentially it picks the next or previous sibling (depending on the key pressed) and call the click event that will in turn display the appropriate image in the gallery. These images are all stored in a unordered list.

Where I am stumped is that when the first or last image is selected and the left or right button is clicked (respectively), I want it to get the next picture at the opposite end of the list of images. For example, if the first image is selected and the left arrow is pressed; given that there is no previous image (or li element), it will get the last image in the list. This way the keys never lose functionality.

Is there a function in jquery that will either check if the present element is the first or last child of its parent, or return its index relative to its parent so I can compare its index to the size() (child count) of his parent element?

like image 812
Prusprus Avatar asked Feb 02 '23 13:02

Prusprus


2 Answers

You can use the is()[docs] method to test:

if( $(".thumb-selected").is( ':first-child' ) ) {
    // whatever
} else if( $(".thumb-selected").is( ':last-child' ) ) {
    // whatever
}
like image 197
user113716 Avatar answered Feb 05 '23 15:02

user113716


You can do this in native JavaScript like so:

var thumbSelected = document.querySelector('.thumb-selected');

var parent = thumbSelected.parentNode;

if (thumbSelected == parent.firstElementChild) {
    // thumbSelected is the first child
} else if (thumbSelected == parent.lastElementChild) {
    // thumbSelected is the last child
}
like image 45
beingmrkenny Avatar answered Feb 05 '23 16:02

beingmrkenny