简体   繁体   中英

Jquery to add style to the element

I have a div like this...

<div class="service_circle">
    <i class="fa fa-briefcase service_circle_icon"></i>
    <h5 class="service_circle_heading">Briefcase details</h5>
    <p class="service_circle_desc">We provide professional website design</p>
</div>

I want to apply style="background-color:red;" to the <i> element using jQuery. I have written something like this:

<script type="text/javascript">
    $(document).ready(function () {
        $(".service_circle").mouseenter(function () {
            $("this").next("i").attr("style", "background-color:red !important;");
        });
    });
</script>

It is not working. Kindly help me to solve this.

Use the find() to get the child i element and the css() method instead:

$(this).find("i").css("background-color", 'red');

Also note that it is better practice to set your styling in CSS and add classes to elements. Try this:

.red { color: red; }
$(this).find("i").addClass('red');

You need to use .find() to get the child i then use .css() method.

$(".service_circle").mouseenter(function () {
    $(this).find("i").css("background-color","red");
});

And this should not be in quotes. it refers to element which invoked the event.

HI now you can used to css

CSS : hover Selector

.service_circle:hover i{
background-color:red;
}
$(".service_circle").hover(function () {
    $(this).find("i").addClass('red');
},
    $(this).find("i").removeClass('red');
);

Better approach with addClass and removeClass using hover

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