Marius Djerv
Marius Djerv

Reputation: 265

Add class to parent element

I know this has been asked many times before, but I could not find anything that worked. I will need to add a class to a div that gets autogenerated over my ul.

This is my html code:

<div class="wrapper">
    <ul id="bx-pager">
       <li><a><img></a></li>
       <li><a><img></a></li>
    </ul>
</div>

I need to add a second class to div class "wrapper", but after what I have tried I can't get it to work. I would be nice if someone can help me out with this simple task, but showing me how to do it. I don't have much experience with jQuery, but need it now.

Upvotes: 2

Views: 22060

Answers (4)

Mo.
Mo.

Reputation: 27533

In pure javaScript

this.parentElement.classList.add('newClass');

Updated

const myElement = document.querySelector('#bx-pager');
myElement.parentElement.classList.add('new-class');
.new-class {
  background-color: tomato;
}
<div class="wrapper">
  <ul id="bx-pager">
    <li>
      <a><img></a>
    </li>
    <li>
      <a><img></a>
    </li>
  </ul>
</div>

Upvotes: 5

jacquard
jacquard

Reputation: 1307

Since you specified that you are new to query: here is the link to the working example.

Upvotes: 0

Suhas Gosavi
Suhas Gosavi

Reputation: 2180

Its simple find parent and add new class. You can use following code to find any parent and add new class.

$(this).parent().addClass('newClass');

Upvotes: 0

Jonathan
Jonathan

Reputation: 1833

You can use the JQuery parent selector:

$('#bx-pager').parent('div').addClass('newClass');

Upvotes: 6

Related Questions