custom selectors

CSS Selectors

not first child

/* not first child */
:not(:first-child)

/* starting from 2nd child */
:nth-child(n+2)

/* next sibling */
A + A

JS Selector Functions

// $ ⭐️
function $(selector, parent = document){
  return parent.querySelector(selector);
}

// $all ⭐️
function $all(selector, parent = document){
  return parent.querySelectorAll(selector);
}

// ⭐️ element.$('div')
// ⭐️ 注意:prototype method 必須放前面,不能擺最後面❗️
Element.prototype.$ = function(selector){
    return this.querySelector(selector);
}

// test run
console.log($('div'));              // HTMLDivElement
console.log($('div').$('span'));    // HTMLSpanElement

Last updated