44 of 119 menu

The closest method

The closest method finds the closest parent element that satisfies the selector specified by the method parameter. This method is similar to the parent method. The search is performed as follows: first, the immediate parent of the element is checked, then the ancestor, the great-grandparent, and so on until the root element (that is, until the html tag).

Syntax

The selector can be a DOM element, an expression, or a jQuery object. The search starts from the DOM element passed as a parameter:

.closest(selector);

The second parameter can also be a DOM element, then the search will be performed in this element:

.closest(selector, context);

Example

Let's find the closest parent with class www for the element with #test and insert a paragraph with text '!' at the beginning of this element, and a paragraph with text '?' at the end:

<div> <div class="www"> <div> <p id="test">text</p> </div> </div> </div> $('#test').closest('.www').append('<p>?</p>').prepend('<p>!</p>');

HTML the code will look like this:

<div> <div class="www"> <p>!</p> <div> <p id="test">text</p> </div> <p>?</p> </div> </div>

See also

  • method parent,
    which allows you to get the immediate parent of an element
  • method parents,
    which allows you to get all the parents of an element
  • method parentsUntil,
    which allows you to get all the parents of an element up to the specified parent
  • JavaScript method closest,
    which allows you to get the closest parent element
azbydeenesfrkakkptruuz