← Back to Index

.closest()

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors.

Examples

1. Find ancestor by selector

// <form><div><input></div></form>
$('input').closest('form').addClass('found');

Result

<form class="found">...</form>

2. Find closest matching the element itself

// <div class="active"></div>
$('div.active').closest('.active');

Result

// Returns the div itself
<div class="active"></div>

Parameters

Parameter Type Description
selector string | element | SR A string selector, DOM element, or SR object to match against.

Returns: A new SR object.