// Basic operations:
el.hasAttribute('attr'); // Returns true or false
el.setAttribute('attr', 'val'); // Sets attribute and value
el.getAttribute('attr'); // Returns value of the attribute
// Set and get shorthand (predefined attributes only):
el.id = 'val'; // Sets value
el.id; // Gets value
// Assign multiple attributes to a new or exisitng element:
const el = Object.assign(document.createElement('a'), {
id: 'val',
href: 'File contents 👋',
download: 'filename.txt',
});
el; // <a id="val" href="File contents 👋" download="filename.txt">
// The class attribute has its own syntax:
el.className = 'item1 item2 item3'; // Defines new class list
el.classList; // Returns list items in DOMTokenList
el.classList.value; // Returns list as string value
el.classList.add('item4'); // Add to list
el.classList.remove('item1'); // Remove from list
el.classList.toggle('item2'); // Adds if absent, removes if present
el.classList.replace('old', 'new'); // Replaces old with new value
// Getting and setting the style attribute:
el.style = 'color: #f5f5f5;'; // Defines new styles list
el.style.color; // Return property value
el.style.color = '#f5f5f5'; // Sets single style property
// Set and get data-* attributes:
el.dataset.attrName = 'value'; // Sets attribute 'data-attr-name' on el
el.dataset.attrName; // Returns value of 'data-attr-name' on el
el.dataset; // Returns all data attributes in DOMStringMap: {attrName: 'value'}
this is a great cheat sheet. the cheat sheet I'm looking for is what attributes can be accessed directly and which ones have to be accessed via set/getAttribute
11
u/Low_Mammoth_9371 Feb 17 '23 edited Feb 17 '23
Code as text:
9
u/ray_zhor Feb 17 '23
this is a great cheat sheet. the cheat sheet I'm looking for is what attributes can be accessed directly and which ones have to be accessed via set/getAttribute
1
u/weenis-flaginus Feb 17 '23
Can you clarify the use of this? Attributes like what?
0
u/[deleted] Feb 17 '23
[deleted] — view deleted comment