简体   繁体   中英

accessing a href element inside li ul

I have my DOM elements as below

在此输入图像描述

i want to access 3rd "a href" element inside "ul class='dropdown-menu dropdown-caret'" and change it's class "colorpick-btn" to "colorpick-btn selected" and set the class of first "a href" element to "colorpick-btn".

I was only able to come up with below but i can not get it working

<script>
        $(document).ready(function () {

            $("#dropdown-menu dropdown-caret li a").removeClass('colorpick-btn').addClass('colorpick-btn selected');

        });
    </script>

Use li:nth-child(3) a for the first one, and :first-child for the second.

jsFiddle example - it appears to do what you are asking.

$(".dropdown-menu.dropdown-caret li:nth-child(3) a").addClass('selected');
$(".dropdown-menu.dropdown-caret li:first-child a").removeClass('selected');

Aside from that, use .dropdown-menu.dropdown-caret as opposed to #dropdown-menu dropdown-caret ..

var $ul = $('.dropdown-colorpicker .dropdown-caret');
$ul.find('.colorpick-btn.selected').removeClass('selected');
$ul.find('.colorpick-btn').eq(2).addClass('selected');

In your markup, you don't have any elements with id dropdown-menu. Also, dropdown-menu and dropdown-caret are referencing the same element and should not be separated by a space. This should get you started:

$(document).ready(function (){
    $(".dropdown-menu.dropdown-caret li:eq(2) a").removeClass('colorpick-btn').addClass('colorpick-btn selected');
});

you can simply use nth-child for this. no need to remove existing class, after selecting element you want, you can add new class like bellow

<script>
    $(document).ready(function () {

        $("#dropdown-menu dropdown-caret li:nth-child(3) a").addClass('selected');

    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM