JavaScript shortcuts DOM Element Helper Functions for fast coding

MD M Nauman Wednesday, 14 March 2018 2 comments


Hello! Friends I was working on a website and was just using JavaScript, not any library as it was the demand. So I thought I should create a helper function that could make our code shorter like for example I have a div element with the ID of the container. I need to select it and assign it to a variable.

Normally we have to select it like this:

Example:

var container = document.getElementById("container");

If I need to select more elements with the id's then the same code will be repeated just the difference in id's

So to make it simple like in JQuery we select the same Id in this way:

Example:

var container = $("#container");

See how JQuery saved our time but here if we don't want to use any library then what? that's why I have created a helper function. That will work similar to jquery or easier then Jquery.

This is the function we have created a helper function to get the id of the element.

function $(h){    var idSelector = document.getElementById(h);    return idSelector;}
Here we have created a function with the name of $ (dollar) and it accepts a parameter.

In this function, we have assigned a variable idSelector and given the value of document.getElementById(h);

After declaring, it will return the variable.

Now after using this function, we can get the Id of the element similar to jQuery

Example: if you have a div with the id of a container:

<div id="container">Hello, All blogger tricks</div>

Now to get the id we just need to call the above callback function:\

var content = $("container"); // Here we are calling the function name i,e $ and the parenthesis and the id name.

We will update this post as we create more helper function to get elements by tag and class name also.
Labels:

Sharing is Caring:

2 Comments to JavaScript shortcuts DOM Element Helper Functions for fast coding Post Yours! Read Comment Policy ▼

Admin please suggest me a blogger template....please reply

Hello, We can create your desired template. If you want then contact us.