Find parent and first child of it's parent

2019-04-05 03:07发布

问题:

I am trying to find the parent of an element and it's parent first child, the code is like this:

        <ul class="lowerMenu">
            <li><a href="" class="selected">Welcome</a></li>
            <li><a href="">Logo</a></li>
            <li><a href="">Websites</a></li>
            <li><a href="">Stationery</a></li>
            <li><a href="">Illustration</a></li>
            <li><a href="">Full Pack</a></li>
        </ul>

function setIntervalAndExecute() {
    changeImages();
    setTimeout(function(){
        showImages(imagesArray);
    },500);
    var intervalot = window.setInterval(function(){
        changeImages();
        var selected = $('.selected');
        if (!selected.parent().is(':last-child')) {
            $('.selected').parent().next().children().addClass('selected');
            selected.removeClass('selected');
        } else {
            $('.selected').parent().parent().children(':first-child').addClass('selected');
            selected.removeClass('selected'); // nesho ne mi rabotit ovdeki
        }
        window.setTimeout(function(){
            showImages(imagesArray);
        },500);
    },10000);
    return intervalot;
}
var intervalot = setIntervalAndExecute();

I know it's a little complicated but i'm new to jquery , so what i'm trying to do is after the class 'selected' gets to the last element i want to remove it and set it to the first element. I've tried with this but it doesn't seem to be working

$('.selected').parent().parent().children(':first-child').addClass('selected');

and when it gets to the last element the interval is executing twice and then stops. This is the site that i'm working on:

http://nikodola.com/testsite

回答1:

If you go up two levels, then find the next child, you're only going down one level -- you're setting the selected class on the <li>, not the <a> below it.. You need to go down another level. So it should be:

$('.selected').parent().parent().children(':first-child').children().addClass('selected');

Another way to get there is:

$('.selected').parent().siblings(':first-child').children().addClass('selected');


回答2:

$('.selected').parent().siblings(':first-child').children().addClass('selected');

FIDDLE DEMO



回答3:

$('.selected').closest('ul').find('li:first').addClass('selected');

reference closest



回答4:

There is no need of total traversing back to the parent one after the other in a hierarchy, you can just do use parents() instead of parent() in this way

$('.selected').parents('ul.lowerMenu').children(:first-child').addClass('selected');

Try it this is working!!