CSS-TricksJavaScript Snippets Feed | CSS-Tricks https://css-tricks.com Tips, Tricks, and Techniques on using Cascading Style Sheets. Fri, 17 May 2024 19:27:47 +0000 hourly 1 https://wordpress.org/?v=6.5.2 https://i0.wp.com/css-tricks.com/wp-content/uploads/2021/07/star.png?fit=32%2C32&ssl=1 JavaScript Snippets Feed | CSS-Tricks https://css-tricks.com 32 32 45537868 The .classList() API https://css-tricks.com/snippets/javascript/the-classlist-api/ https://css-tricks.com/snippets/javascript/the-classlist-api/#comments Mon, 20 Apr 2020 13:58:03 +0000 Chris Coyier https://css-tricks.com/?page_id=306845 Assuming you have an element in the DOM:

<div id="el"</div

Get a reference to that DOM element:

const el = document.querySelector("#el");

Then you can manipulate the classes on that element with the classList method.

// Add a class
el.classList.add("open");

…]]>
Assuming you have an element in the DOM:

<div id="el"></div>

Get a reference to that DOM element:

const el = document.querySelector("#el");

Then you can manipulate the classes on that element with the classList method.

// Add a class
el.classList.add("open");

// Add many classes
el.classList.add("this", "little", "piggy");
let classes = ["is-message", "is-warning"];
el.classList.add(...classes);

// Remove a class
el.classList.remove("open");

// Remove multiple classes
el.classList.remove("this", "little", "piggy");

// Loop over each class
el.classList; // DOMTokenList (pretty much an array)
el.classList.forEach(className => {
  // don't use "class" as that's a reserved word
  console.log(className);
});
for (let className of $0.classList) {
  console.log(className);
}

el.classList.length; // integer of how many classes there are

// Replace a class (replaces first with second)
el.classList.replace("is-big", "is-small");

// Toggle a class (if it's there, remove it, if it's not there, add it)
el.classList.toggle("open");
// Remove the class
el.classList.toggle("open", false);
// Add the class
el.classList.toggle("open", true);
// Add the class with logic
el.classList.toggle("raining", weather === "raining");

// Check if element has class (returns true or false)
el.classList.contains("open");

// Look at individual classes <div class="hot dog">
el.classList.item(0); // hot
el.classList.item(1); // dog
el.classList.item(2); // null
el.classList[1]; // dog

Browser Support

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

ChromeFirefoxIEEdgeSafari
282611127

Mobile / Tablet

Android ChromeAndroid FirefoxAndroidiOS Safari
1241254.47.0-7.1
]]>
https://css-tricks.com/snippets/javascript/the-classlist-api/feed/ 2 306845
Inject HTML From a String of HTML https://css-tricks.com/snippets/javascript/inject-html-from-a-string-of-html/ https://css-tricks.com/snippets/javascript/inject-html-from-a-string-of-html/#comments Thu, 19 Mar 2020 14:49:58 +0000 Chris Coyier https://css-tricks.com/?page_id=305098 Say you have some HTML that is a string:

let string_of_html = `
  <divCool</div`;

Maybe it comes from an API or you’ve constructed it yourself from template literals or something.

You can use innerHTML to put that into …

]]>
Say you have some HTML that is a string:

let string_of_html = `
  <div>Cool</div>
`;

Maybe it comes from an API or you’ve constructed it yourself from template literals or something.

You can use innerHTML to put that into an element, like:

document.body.innerHTML = string_of_html;

// Append it instead
document.body.innerHTML += string_of_html;
(more…)]]>
https://css-tricks.com/snippets/javascript/inject-html-from-a-string-of-html/feed/ 2 305098
Required Parameters for Functions in JavaScript https://css-tricks.com/snippets/javascript/required-parameters-for-functions-in-javascript/ https://css-tricks.com/snippets/javascript/required-parameters-for-functions-in-javascript/#respond Thu, 02 Jan 2020 20:53:13 +0000 Chris Coyier https://css-tricks.com/?page_id=301276 Ooo this is clever! I’m snagging this from David’s blog.

const isRequired = () => { throw new Error('param is required'); };

const hello = (name = isRequired()) => { console.log(`hello ${name}`) };

// These will throw errors
hello();
…]]>
Ooo this is clever! I’m snagging this from David’s blog.

const isRequired = () => { throw new Error('param is required'); };

const hello = (name = isRequired()) => { console.log(`hello ${name}`) };

// These will throw errors
hello();
hello(undefined);

// These will not
hello(null);
hello('David');

(more…)

]]>
https://css-tricks.com/snippets/javascript/required-parameters-for-functions-in-javascript/feed/ 0 301276
Remove Duplicates from an Array https://css-tricks.com/snippets/javascript/remove-duplicates-from-an-array/ https://css-tricks.com/snippets/javascript/remove-duplicates-from-an-array/#respond Mon, 16 Dec 2019 20:47:27 +0000 Chris Coyier https://css-tricks.com/?page_id=300561 Compiled by Svein Petter Gjøby:

const array = [1, 1, 1, 3, 3, 2, 2];

// Method 1: Using a Set
const unique = [...new Set(array)];

// Method 2: Array.prototype.reduce
const unique = array.reduce((result, element) => {
  return result.includes(element) 
…]]>
Compiled by Svein Petter Gjøby:

const array = [1, 1, 1, 3, 3, 2, 2];

// Method 1: Using a Set
const unique = [...new Set(array)];

// Method 2: Array.prototype.reduce
const unique = array.reduce((result, element) => {
  return result.includes(element) ? result : [...result, element];
}, []);

// Method 3: Array.prototype.filter
const unique = array.filter((element, index) => {
  return array.indexOf(element) === index;
});
]]>
https://css-tricks.com/snippets/javascript/remove-duplicates-from-an-array/feed/ 0 300561
Getting First and Last Items in Array (and splitting all the rest) https://css-tricks.com/snippets/javascript/getting-first-and-last-items-in-array-and-splitting-all-the-rest/ https://css-tricks.com/snippets/javascript/getting-first-and-last-items-in-array-and-splitting-all-the-rest/#respond Tue, 30 Oct 2018 14:05:00 +0000 Chris Coyier https://css-tricks.com/?page_id=305227 I needed to get the first item from an array lately in JavaScript. Hmmmm … lemme think here. I remember that .pop() is for snagging the last item from the array, like this:

const arr = ["This", "Little", "Piggy"];
const 
…]]>
I needed to get the first item from an array lately in JavaScript. Hmmmm … lemme think here. I remember that .pop() is for snagging the last item from the array, like this:

const arr = ["This", "Little", "Piggy"];
const first = arr.pop();
console.log(first);
// "Piggy"

So what’s the opposite of .pop()? (Please pause for light web searching…) Ah ha! It’s .shift()!

const arr = ["This", "Little", "Piggy"];
const first = arr.shift();
console.log(first);
// "This"

(Note that arr[0] is probably the easiest way to get the first item, but play along here. Also, it’s kinda nice sometimes if what is cut off from the array remains an array so let’s keep looking…)

But when I reached for this wonderful little helper method, I stopped in my tracks! Not everyone will run into this issue because it’s not a problem with arrays in general but with arrays in certain contexts. This is what I saw in the codebase I was working on:

The issue is that I was trying to pull this item from an array in which I was not allowed to manipulate. In my case, I was using Apollo GraphQL and the data that I was getting back was in the form of a read-only property.

Read-only? All I’m trying to do here is ask for the first item in an array: I’m not changing anything. OR AM I? (I am.) Turns out both .pop() and .shift() will return those last and first items respectively, but they’ll also manipulate the original array. And my array was un-manipulatable.

What I actually needed was to take an array and get both the first item and all the rest of the items in a new array, while leaving the original array alone! The .slice() array method had my back here nicely. It won’t mess with the original array.

This will do us nicely:

const arr = ["This", "Little", "Piggy"];
const first = arr.slice(0, 1);
const the_rest = arr.slice(1);console.log(first); // ["This"]
console.log(the_rest); // ["Little", "Piggy"]

Hey, just what I needed!

Need an easy way to find the correct array method you need? Try Sarah Drasner’s JavaScript Array Explorer:

]]>
https://css-tricks.com/snippets/javascript/getting-first-and-last-items-in-array-and-splitting-all-the-rest/feed/ 0 305227