chamara
chamara

Reputation: 12709

accessing a href element inside li ul

I have my DOM elements as below

enter image description here

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>

Upvotes: 0

Views: 834

Answers (4)

Chanuka Asanka
Chanuka Asanka

Reputation: 3004

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>

Upvotes: 0

Josh Crozier
Josh Crozier

Reputation: 240928

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..

Upvotes: 1

maiorano84
maiorano84

Reputation: 11951

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');
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

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

Upvotes: 1

Related Questions