Nathan
Nathan

Reputation: 87

Using jQuery to target (this) not working as expected

I'm trying my hands on some jQuery and there is some part I don't understand. It's also hard for me to google because I'm not quite sure of the terminology - hence why I am asking the question and will explain my exact intentions.

Here is my HTML markup.

<div class="contentLarge">

<a href=""><header>Use responsive design.</header></a>

<div class="contentFlex">
    <div class="contentFlex1"></div>
    <div class="contentFlex2"></div>
</div>

Now what I want is that when I hover over the anchor link, the background of the entire contentLarge container changes. I have several of these containers on my page.

Here is the jQuery:

$(document).ready(function(){
    $(".contentLarge header").mouseenter(function(){
        $(".contentLarge").css({"background-color": "red"})
    });
});

Now I understand that now when I hover - each contentLarge container will get it's background changed to red. This is not what I want.

But when I try using the $(this) selector for targetting within this function - it's the HEADER that gets changed, not the contentLarge. Like so;

$(document).ready(function(){
    $(".contentLarge header").mouseenter(function(){
        $("this").css({"background-color": "red"})
    });
});

How do I write it so that $(this) is the target container - changing only it's background to red instead of either all containers, or only the header.

Upvotes: 0

Views: 35

Answers (1)

Jasper
Jasper

Reputation: 631

Use parent() to point at the .contentLarge container that holds the link you hover over:

$(document).ready(function(){
    $(".contentLarge header").mouseenter(function(){
        $(this).parent().css({"background-color": "red"})
    });
});

Another options would be to use closest(), which searches for the closest intance with the .contentLarge class. Useful to prevent using .parent().parent().parent()... when there are multiple layers between your .header and the .contentClass.

$(document).ready(function(){
    $(".header").mouseenter(function(){
        $(this).closest('.contentLarge').css({"background-color": "red"})
    });
});

Upvotes: 1

Related Questions