HTML DOM Element closest() method
- 上一页 cloneNode()
- 下一页 compareDocumentPosition()
- 返回上一层 HTML DOM Elements 对象
Definition and usage
closest()
the method searches for elements in the DOM tree that match the specified CSS selector.
closest()
the method starts from the element itself and then goes up the ancestors (parent, grandparent element, ...) until a match is found.
if no match is found closest()
method returns null
.
see also:
instance
Example 1
Find the closest element that matches the CSS selector ".container":
const element = document.getElementById("myElement"); const closest = element.closest(".container");
Example 2
Find the closest element that matches ".container" or ".wrapper":
const element = document.getElementById(".container, .wrapper"); const closest = element.closest(".container");
syntax
element.closest(selectors)
parameter
parameter | description |
---|---|
selectors |
required. One or more (comma-separated) CSS selectors to match. see our complete CSS 选择器参考手册. |
return value
type | description |
---|---|
object |
the closest ancestor element or element itself that matches the specified CSS selector. null is returned if no match is found. SYNTAX_ERR exception is triggered if the selector is invalid. |
browser support
fully supports the first closest()
browser version of the method:
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome 41 |
Edge 15 |
Firefox 35 |
Safari 9 |
Opera 28 |
2015 年 3 月 | 2017 sanata 4 oktoba | 2015 sanata 1 oktoba | 2015 sanata 10 oktoba | 2015 年 3 月 |
- 上一页 cloneNode()
- 下一页 compareDocumentPosition()
- 返回上一层 HTML DOM Elements 对象