javascript : .closest(cssSelector)
javascript : .closest(cssSelector)
Target:
Applicable with any DOM element.
- getElementById
- getElementsByTagName
- getElementsByClassName
- getElementsByName
- querySelector
- querySelectorAll
- select
- etc.
Description :
it search for closest parent element that matched with the selector. It traverse parentNode to parentNode untill matched with selector if no any parent element matched then it return empty array of nodeElementsList instead of null so nested statement not generate error due to null reference.
Note : it start searching of selector from the element itself. That's mean if the element matches with the selector it return itself.
Syntax:
DOMElement.closest(cssSelector)
DOMNodeList.closest(cssSelector)
HTMLCollection.closest(cssSelector)
Usase:
- document.getElementById('firstDiv').closest('form')
it search for firstDiv Element's parent form. - document.getElementsByTagName('div').closest('form')
the getElementsByTagName selects all div and closest() method return first element's parent form. - document.getElementsByClassName('FirstDiv').closest('form')
the getElementsByClassName selects all elements having class FirstDiv and closest() method return first element's parent form. - document.getElementsByName('FirstDiv').closest('form')
the getElementsByName selects all elements having name attribute "FirstDiv" and closest() method return first element's parent form. - document.querySelector('.FirstDiv').closest('form')
the querySelector selects first div having class "FirstDiv" and closest() method return it's parent form. - document.querySelectorAll('.FirstDiv').closest('form')
the querySelectorAll selects all elements having class FirstDiv and closest() method return first element's parent form.
Download MYJS.js
MyJs
is a collection of java script extension methods that enhances the JavaScript
objects, class object, DOM element, domElementsCollections, Date, String, Number
and other data type.
Include
in you project landing page (master page) and it will extends your DOM and
JavaScript Objects.
Comments
Post a Comment