Answer the question
In order to leave comments, you need to log in
How to make a short function for forEach?
Hello.
1. I do not want to use jQuery, but I need a trick from there with applying parameters to an array of objects (sorry if I used the wrong terms).
I mean this $(".block").addClass("red")
And if there are multiple objects with class block then addClass will be applied to all objects. In pure JS I do it like this:
document.querySelectorAll(".block").forEach((el)=> {
el.classList.add("red");
});
function qsf(e) {
return
document.querySelectorAll(e).forEach((el)=> {
el
})
}
function q(e){return document.querySelector(e)}
function qs(e){return document.querySelectorAll(e)}
document.getElementsByClassName("block").forEach((el)=> {
el.classList.add("red");
});
Answer the question
In order to leave comments, you need to log in
Question: How is this the right decision? Am I slowing down the code this way? After all, I make it constantly call the function. Maybe it has something to do with the RAM?
Why before, when I saw js code, they constantly wrote getElementById or getElementsByClassName
Prompt how to be with function which would do forEach?
qsf('.elements', el => el.classList.add("red"));
qsf('.elements').addClass('class-name');
1. Why is there return
if the function should not return anything to you, but just hang classes?
function qsf(e) {
document.querySelectorAll(e).forEach((el)=> {
el.classListt.add('red');
})
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question