My javascript is only working with ID. Not working with Class

Viewed 68

I have a autoclick script which is working with javascript. But it is working only with ID. I need to add it multiple section of page. I tried getElementsByClassName and getElementByClassName. But it was failed. Please convert it from ID to class name.

Not Working with Class

<a href="https://www.google.com" class="hello-btn" target="blank">Google</a>

<script>
var helloBtn = document.getElementByClassName("hello-btn");

helloBtn.addEventListener("click", () => {
  console.log("Btn clicked");
});

var interval = window.setInterval(() => {
  helloBtn.click();
}, 4000);
</script>

Working with Class

<a href="https://www.google.com" id="hello-btn" target="blank">Google</a>

<script>
var helloBtn = document.getElementById("hello-btn");

helloBtn.addEventListener("click", () => {
  console.log("Btn clicked");
});

var interval = window.setInterval(() => {
  helloBtn.click();
}, 4000);
</script>
5 Answers

The function is called getElementsByClassName. It can return multiple results and if you want to attach a handler to all of the returned results, you need to iterate over them:

<a href="#"class="hello-btn">Google</a>
<a href="#"class="hello-btn">Microsoft</a>
<a href="#"class="hello-btn">Facebook</a>
<a href="#"class="hello-btn">Azure</a>
<a href="#"class="hello-btn">AWS</a>
const buttons = document.getElementsByClassName("hello-btn");

Array.from(buttons).forEach((helloBtn) => {
    helloBtn.addEventListener("click", (evt) => {
      console.log(`clicked button ${evt.target.innerHTML}`);
    });
});

Please note, that getElementsByClassName does not return an array, but an array-like object: The HTMLCollection https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection?retiredLocale=de

Update: To get the desired auto click functionality working, you could go like this:

var autoclickInterval = setInterval(()=> {
  Array.from(buttons).forEach((helloBtn) => {
      helloBtn.click()
  });
}, 5000)

//clearInterval(autoclickInterval)

There is no method like getElementByClassName. But getElementsByClassName (note the "s"). simply get the first element from array.

var helloBtn = document.getElementsByClassName("hello-btn")[0];

should work as intended.

Have you tried with const helloBtn = document.querySelector(".hello-btn"); or querySelectorAll?

// Use const instead var
const helloBtn = document.querySelector(".hello-btn");

helloBtn.addEventListener("click", () => {
  console.log("Btn clicked");
});

const interval = window.setInterval(() => {
  helloBtn.click();
}, 4000);

Then you can use <a href="https://www.google.com" class="hello-btn" target="blank">Google</a> with class selector.

As the class name can be used by multiple tags. document.getElementsByClassName returns an Array.

If you want to allow click to all buttons having the same class name. Example: https://jsfiddle.net/pLtjo5hn/

  var helloBtn = document.getElementsByClassName('hello-btn');
  
  for(var i = 0; i < helloBtn.length; i++ ){
    var btn = helloBtn[i];
    btn.addEventListener('click', function handleClick(event) {
      console.log('btn clicked', event.target.innerText, event);
    });

If you want to allow click to only 1st element/button having the same class name. Example: https://jsfiddle.net/0vnos7xr/

    var helloBtn = document.getElementsByClassName('hello-btn')[0];

    helloBtn.addEventListener('click', function handleClick(event) {
      console.log('btn clicked', event.target.innerText, event);
    });

Note: If there is just 1 button to bind a click event, it is always better to use ID instead of Class Name.

Related