Only Javascript Please

For every front-end developer — Javascript is the most important skill. Irrespective of how many libraries are out there yet every developer should be very strong in javascript.

Frameworks will keep coming and going but in long-term career you should know how Javascript works. Under the hood , every framework and library is the javascript only. If you will check the interview questions of most of the companies they are also around your knowledge in javascript only.

In this article, I am going to share few basics yet most used javascript code that every front-end developer use in his daily code-life. Most of the time we lookup at the jQuery or other frameworks/libraries for these tasks but they can be easily done by Javascript too.

1. Access DOM Elements on the basis of class

The most used method to access DOM elements in Javascript is by document.getElementById. For this we need to assign ID to DOM element which we want to access. But what if you want to access an element based on class or just with tag name.

document.getElementsByClassName(‘classname’);

This will return an array of result matching the class. As classes in DOM could be more than once hence we will always get the array.

2. Read the input field value

When we are developing interactive websites or apps. Getting the user inputs and manipulating them is the most used task. Most of the time we ask users to fill a form or to enter some information on basis of that we show them results. From javascript doing this is very easy.

document.getElementsByTagName(‘input’)[0].value;

3. Add CSS styling to DOM elements

There are many situations where we need to add custom css through Javascript. From changing the color, font-size or changing the visibility of the elements on the fly on some interaction requires the javascript to add the styles in DOM.

It is very simple to do same in Javascript. The pain could be writing repetitive syntax.

document.getElementsByClassName(‘classname’).style.backgroundColor = “red”;

4. Add/remove/append classes in DOM

Javascript is heavily dependent on playing with classes in DOM when it comes to adding interactivity. You can achieve a lot by just playing with CSS. Also, if you are writing too much — “<element>.style.<styleProperty>” then you should consider making a class and adding/removing it from DOM

document.getElementsById(‘classname’).className = “newClassName”;

Here is the running code — enjoy!!

Thank you guys for reading it. I would love to hear your thoughts on same. If you are a jslovers do not forget to join — meetup.com/jslovers.