ancestors

ancestor Methods

  • Methods used to get the ancestors of the selected element

.parent()

  • Method is used to get the direct parent of the selected element

Example

$(() => {
  $('button').click(() => {
    $('.box').parent().toggleClass('backgroundEffect')
  })
})

JS Bin on jsbin.com


.parents()

  • Method is used to get the ancestors of the selected element

Example

$(() => {
  $('button').click(() => {
    // this will apply the class to "all" ancestors
    $('.box').parents().toggleClass('backgroundEffect')

    // uncomment the line below and observe the difference; we are using method chaining here to target only the "grandparent" of the black box
    //$('.box').parent().parent().toggleClass('backgroundEffect')
  })
})

JS Bin on jsbin.com