How can I make this more efficient?

Hi, my HTML has the following code:

Click me to change the header color!
Click me to change the footer color!
Click me to change the nav color!

the problem is that all fucntions are the same, I have it like this because the HTML elements all have different id’s, demo, demo1 and demo2, so the functions look like this:

function cambiar(){
document.getElementById(“demo”).style.backgroundColor = mensaje();


function cambiar1(){

document.getElementById("demo1").style.backgroundColor = mensaje();


function cambiar2(){

document.getElementById("demo2").style.backgroundColor = mensaje();


how can I improve this? thanks for the help!

I guess you could include a data attribute for the html elements and use .dataset to access that attribute in the javascript.

<p data-targeted="demo">Click me to change the header color!</p>
<p data-targeted="demo1">Click me to change the footer color!</p>
<p data-targeted="demo2">Click me to change the nav color!</p>
function mensaje() {
  return "red";

function cambiar(event) {
  const id = this.dataset.targeted; // or;
  document.getElementById(id).style.backgroundColor = mensaje();

for (let element of document.querySelectorAll(`*[data-targeted^="demo"]`)) {
  element.addEventListener("click", cambiar);

this is very advanced, I’ll try it, thanks!!


As a contradiction to the title, JS used in an HTML setting is neither more, nor less efficient. It is top down during the page build stage, and event driven during the run session. We do not need to concern ourselves with efficiency for this purpose. Just well formed HTML and well formed and valid script. The browser has all the resources it needs to perform all this stuff in the blink of an eye.

Where we become concerned about efficiency is when we are using JS in a programmatic way such as crunching numbers, working with large data sets, iterating, and so on. These are the things that can be more or less efficient, depending upon complexity. A task can be done in several ways. That is where we need to focus on efficiency. HTML? Naw. If it works, it is efficient enough.

1 Like

Added aside

On the topic of events and event listeners: We should always consider the load on the system. Listeners are live, real time, asymmetric loads on the real time system.
The more we have active, the greater the real time load. Take the time to study how to reduce this load using delegation when designing event driven applications.

thanks! this was very helpful, I guess my question was more in the line of how I could write the same program but without having to use different functions, since I was using different id’s for the HTML tags, each id was linked to a different function, except it was all the same function, to change the background color, but I appreciate your comments.

1 Like