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:

  1. document.getElementById('firstDiv').closest('form')
    it search for firstDiv Element's parent form.
  2. document.getElementsByTagName('div').closest('form')
    the getElementsByTagName selects all div and closest() method return first element's parent form.
  3. document.getElementsByClassName('FirstDiv').closest('form')
    the getElementsByClassName selects all elements having class FirstDiv and closest() method return first element's parent form.
  4. document.getElementsByName('FirstDiv').closest('form')
    the getElementsByName selects all elements having name attribute "FirstDiv" and closest() method return first element's parent form.
  5. document.querySelector('.FirstDiv').closest('form')
    the querySelector selects first div having class "FirstDiv" and closest() method return it's parent form.
  6. 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

Popular posts from this blog

javascript : String.right

javascript : String.left

javascript : .nextAll()