r/learnjavascript • • Feb 17 '23

How to control HTML element attributes using JS cheatsheet

Post image
158 Upvotes

9 comments sorted by

11

u/Low_Mammoth_9371 Feb 17 '23 edited Feb 17 '23

Code as text:

// 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'}

5

u/senocular Feb 17 '23
download: 'filename.txt,

^ missing closing quote

4

u/Low_Mammoth_9371 Feb 17 '23

Thanks for the spot, corrected in the 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

5

u/Low_Mammoth_9371 Feb 17 '23

Thanks!
Yeah, this issue confused me at first when I started using shorthand. Doesn't work for custom attributes.

1

u/weenis-flaginus Feb 17 '23

Can you clarify the use of this? Attributes like what?

3

u/Low_Mammoth_9371 Feb 17 '23

Attributes on any HTML element, like class and data-src below:

<img class="img" data-src="url-to-image"> 

Attributes are used for a wide variety of reasons, including styling, identifying elements, storing data, setting the source for a resource and more.

0

u/[deleted] Feb 17 '23

[deleted]

4

u/Low_Mammoth_9371 Feb 17 '23

Sure, I created it using Cabron: https://carbon.now.sh/
I think there is an extension for VSC but not one that I have used personally.