Useful JavaScript snippets
In this post, we're listing some useful JavaScript snippets
By: Ajdin Imsirovic 03 November 2019
In this article, we’ll look at some useful JavaScript code snippets. The list of these snippets will be growing, as I’ll revisit this post whenever I get an idea for a new snippet or find a useful one online. I plan to give out kudos too, so if you find your own snippet listed, don’t hesitate to contact me with your details so I can give you proper attribution!
Photo by Christopher Robin Ebbinghaus on Unsplash.com
Mute a webinar video
Sometimes I signup for a live webinar and it really annoys me that I can’t mute it when I feel like it.
Luckily, there’s the JavaScript console.
Here’s the script:
var vid = document.getElementById('player_html5_api');
vid.muted = true;
Check the length of user-provided strings recursively (forever)
I needed to make sure that the title tags for this blog were less then 65 characters, so I wrote a simple script to check it:
var checkIt = () => {
var str = prompt("?");
var len = str.length;
alert(str.length);
checkIt();
}
checkIt(); // to start the first run
The script will just keep going unless I press the ESC key to finish it.
Quickly convert an HTML collection into an Array (2 different ways)
Let’s say you’re trying to grab all h3
elements from the Google search results page. You can do it with the following code:
document.querySelectorAll('h3')
What you’ll get back is an HTML collection. To run some array methods on it, you need to convert it to an array. Like this:
Array.from(document.querySelectorAll('h3'))
Alternatively, you can do it like this:
[...document.querySelectorAll('h3')]
Once converted, you can run various array-specific methods, like forEach
:
[...document.querySelectorAll('h3')].forEach(x => x.style.color = 'tomato')
Alternatively, you can do it like this:
Array.from(document.querySelectorAll('h3')).forEach( x => console.log(x) )
Feel free to play around with this method. For example:
[...document.getElementsByTagName('h3')].forEach(x => x.setAttribute('style', 'background: tomato'))
Check for presence of an object member
Be it a property or a method, here’s how to check if they exist on an object:
- using the
in
operator - using the
hasOwnProperty
method - checking if the member is equal to
undefined
Here’s some code demonstrating the use of all three:
let car = {
color: "gray",
lights: "off",
lightsOn() {
this.lights = "on"
},
lightsOff() {
this.lights = "off"
},
lightsStatus() {
console.log(`The car's lights are ${this.lights}`)
}
}
// (1)
'lightsOff' in car; // returns: true
'lightsBlink' in car; // returns: false
// (2)
car.hasOwnProperty('lightsOff'); // returns: true
car.hasOwnProperty('lightsBlink'); // returns: false
// (3)
car.lightsOff !== undefined; // returns: true
car.ligthsBlink !== undefined; // returns: false
Quickly find and replace all instances of a word
Let’s say we have a string that says: “dog eat dog”, and we want to replace it to “cat eat cat”.
Here’s a quick and easy way to do it:
let str = "dog eat dog";
str = str.split("dog").join("cat");
// returns: "cat eat cat"
Easy, fun, and useful JavaScript snippet here!
Get all the img tags whose src attribute is starting with a specific string
This is an interesting one.
Recently I needed to find all the images on the page that had a specific URL (pointing to a folder with icons). I needed to run a quick test with those images not visible on the screen temporarily.
This is the code I used:
let imgs = document.querySelectorAll("img[src^='https://www.example.com/wp-content/plugins/example-plugin/assets/images']");
[...imgs].forEach(i => i.style="opacity: 0")
It’s a pretty niche implementation, but it might be useful.
To be continued…