How do I add a class to a given element?

前端 未结 25 2451
清酒与你
清酒与你 2020-11-21 11:34

I have an element that already has a class:

25条回答
  •  自闭症患者
    2020-11-21 12:03

    In my case, I had more than one class called main-wrapper in the DOM, but I only wanted to affect the parent main-wrapper. Using :first Selector (https://api.jquery.com/first-selector/), I could select the first matched DOM element. This was the solution for me:

    $(document).ready( function() {
        $('.main-wrapper:first').addClass('homepage-redesign');
        $('#deals-index > div:eq(0) > div:eq(1)').addClass('doubleheaderredesign');
    } );
    

    I also did the same thing for the second children of a specific div in my DOM as you can see in the code where I used $('#deals-index > div:eq(0) > div:eq(1)').addClass('doubleheaderredesign');.

    NOTE: I used jQuery as you can see.

提交回复
热议问题