get/set CSS props
โญ๏ธ ๆณจๆ๏ผ
ไธ่ฆๅฐ Element.getAttribute()ใCSSStyleDeclaration.getPropertyValue() ่ Element.setAttribute()ใCSSStyleDeclaration.setProperty()ๆๆททไบโ๏ธ
// get:
elem.style.color // ไฝฟ็จ <elem style="...">
getComputedStyle(elem).color // โญ๏ธ computed style โ elem.style.colorโ๏ธ
// set:
elem.style.color = 'pink'; // ่จญๅฎๅ
งๅปบๆจฃๅผ
elem.styleProp('--css-var', '4px'); // ่จญๅฎ่ช่จ css var// get
// โญ๏ธ ๆณจๆ๏ผ`elem.style` ๅชๅญๅไพ่ช <... style="..."> ็ๆจฃๅผ, ้ๅธธ็บ ''โ๏ธ
elem.style.backgroundColor
elem.style.getPropertyValue('margin-top') // โญ๏ธ = elem.style.marginTop
// โญ๏ธ computed style (read-onlyโ๏ธ)
// ๆญค่็บใๅฅ็จๆๆๆจฃๅผใๅพๆๅพๅฐ็็ตๆ๏ผๆไปฅไธๅฎๆๅผใ
getComputedStyle(elem).color
// set
elem.style.display = "none"
style.setProperty('margin-top', '4px') // โญ๏ธ style.marginTop = '4px'Element โฉ .styleProp()
MDN โฉ
CSSStyleDeclaration โฉ .setProperty(), .getPropertyValue()
Window โฉ .getComputedStyle()
W3School โฉ CSS Default Values Reference
JS.info โฉ Styles and classes
W3C โฉ Full Property List
Element โฉ .styleProp()
CSS vs. DOM style prop names
'background-color'
elem.style.backgroundColor
'z-index'
elem.style.zIndex
'border-left-width'
elem.style.borderLeftWidth
code example
The style property operates only on the value of the "style" attribute, without any CSS cascade. ๐๐ป See "elem.style" tab below.
String โฉ .capitalize(), .kebabToCamelCase()
Element โฉ .styleProp()
codepen โฉ elem.style
replit โฉ style.setProperty() - set border, backgroundColor, color randomly.
Last updated
Was this helpful?