๐Ÿšงelem.styleProp()

๐Ÿ”ฐ JS โŸฉ DOM โŸฉ Types โŸฉ Element โŸฉ

// โญ๏ธ elem.styleProp(prop[,val])
//    get: 
//         elem.styleProp('padding-left') 
//       = elem.styleProp('paddingLeft')
//       = getComputedStyle(elem).paddingLeft
//       โ‰  elem.style.paddingLeft โ—๏ธ
//    set: 
//         elem.styleProp('padding-left', '8px') 
//       = elem.styleProp('paddingLeft', '8px')
//       = elem.style.paddingLeft = '8px'
Element.prototype.styleProp = function(prop, val=undefined){
  
    const camelCase = !prop.includes('-');
  
    // set prop if necessary
    // โญ๏ธ Note: 
    //    getComputedStyle() is read-only, DO NOT use it to set new value,
    //    use `this.style` insteadโ—๏ธ
    if (val) {
      if (camelCase) this.style[prop] = val;
      else this.style.setProperty(prop, val);  // kebab case
    }
  
    // return prop  
    const style = getComputedStyle(this);
    return camelCase ? style[prop] : style.getPropertyValue(prop);    
};

Last updated

Was this helpful?