We know how fast javascript is growing and evolving with new methods to manipulate the DOM. When you compare vanilla javascript selectors code with jQuery Selectors you will find javascript code is lengthy and repetitive, to avoid this I have created a helper function which will make your coding life little easier and helps you to concentrate more on productivity than the code.
Hey, I have updated the last post and this time we are back with an awesome post.
Here is the code you can create a helperFunctions.js file and paste this below code inside that and add the reference to this file in your HTML page.
If you don't find the above method interesting then add it in the page just add two scripts tags opening and closing and place the code there and use it anywhere.
function sE(element, boolean) {The above function is to select HTML elements to manipulate them whether to select one or all you can do this using one function.
if (element && boolean === false) {
return document.querySelector(`${element}`);
} else {
return document.querySelectorAll(`${element}`);
}
}
Brief Explanation of the Function:
sE: This is the name of the function. I have used a short name you can change this and use whatever you wish.
Arguments:
element: Here you can add id, class, tag name, attribute selector.
for example:
sE("h1", false);
sE(".container", "false");
sE("#id", false);
The above are the examples and the ways how this helper function works. If you are concentrating on reading then you have noticed that why this false value is coming as the next or second argument when invoking the function? let me explain you.
boolean: this is the second argument you have to add true or false based on your project.
True means to select all the elements either of the class, tag name etc
False means to select the single element of that either id, class, tag etc
This is the required field so missing may cause the code to break and produce errors.
Here a complete working example of the above function
let heading = sE("h1", false);
Here in the above example, I'm storing h1 tag in a variable. See how easy it has become to select any elements and to modify them.
Admin please suggest me a blogger template....please reply
ReplyDeleteHello, We can create your desired template. If you want then contact us.
Delete