开发者

How to add css class to parent element?

I am trying to do something rather simple but I am probably missing something...

I have 开发者_StackOverflow社区this code:

var $highlights = $j("div.ab-highlights ul li a");
$highlights.hover(
    function () {
        $j(this).children().addClass('active');

        for (i=0; i < $highlights.length; i++)
        {
            if ($highlights[i] != this)
            {
                console.log(i);
                ($highlights.parent()[i]).addClass('lowOpacity');
            }
        }
    }, 
    function () {
        $j(this).children().removeClass('active');
    }
);

The bottom line is that I am trying attach a class ("lowOpacity") to all elements except the one that I am rolling over. the thing is it won't work. the line that is not working is

($highlights.parent()[i]).addClass('lowOpacity');

What am I missing?


An element can have only one parent.

$j($highlights[i]).parent().addClass('lowOpacity');

This code would add a class to the parent of each highlight element.

You could also refactor your code like this:

var $highlights = $j("div.ab-highlights ul li a");
$highlights.hover(
    function () {
        $j(this).children().addClass('active');
        $j($highlights).not(this).parent().addClass("lowOpacity"); //Thanks Felix +1
    }, 
    function () {
        $j(this).children().removeClass('active');
    }
);


It seems you want to add the class to all parents of the $highlights elements, expect the currently hovered one:

$highlights.not(this).parent().addClass('lowOpacity');

This line of code replaces the whole for loop.

Reference: not

I think you also have to remove the lowOpacity from the elements again. You could reduce your code to this:

var $highlights = $j("div.ab-highlights ul li a");
$highlights.hover(function () {
    $j(this).children().toggleClass('active');
    $highlights.not(this).parent().toggleClass('lowOpacity');
});

Explanation for why your code does not work:

$highlights.parent()[i]

returns a DOM element, but addClass is a jQuery method. Thus you would have to pass it to jQuery again or use eq [docs] instead:

$highlights.parent().eq(i).addClass('lowOpacity');

What this is doing is getting all parent elements of the elements in $highlights and then selecting the ith one.

Another way would be to first select the ith element in $highlights and then its parent.

But as you have seen above, it is much more easier and you don't have to loop at all.


this selects immediate parent

$('your_selector').parent().doSomeThing()

select multiple elements in parent

$('your_selector').parents('selector').doSomeThing()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜