1

I have this code:

<html>
<body>
<script>
function myFunction (){
    // some javascript
}
document.getElementsByClassName('test')[0].setAttribute("onclick", "myFunction()");
</script>
<button class="test"> Submit Request </button>
</body>
</html>

I want to use JavaScript that executes on page load to add an onclick attribute to my button on the page.

Right now in doing this I get an error that says cannot read proprety 'setAttribute' of undefined.

Does anyone know why I am getting this error and how to fix it?

Note: My only option to access the button is via it's class attribute and I cannot physically modify the button element in any way.

Thanks!

Kamui
  • 719
  • 1
  • 9
  • 16
  • 1
    `document.getElementsByClassName('test')` will return `null` as `DOM` is not ready when you are trying to access the elements.. Write your script before closing `body` – Rayon Feb 17 '16 at 04:05

2 Answers2

3

You're getting the error because the element didn't exist when you were trying to access it. You need to perform the event binding operation window.onload event.

window.onload = function(){
    document.getElementsByClassName('test')[0].addEventListener("click", myFunction, false);
}

I would recommend you to use EventTarget.addEventListener() and better use DOMContentLoaded event

document.addEventListener("DOMContentLoaded", function(event) {
      console.log("DOM fully loaded and parsed");
      document.getElementsByClassName('test')[0].addEventListener("click", myFunction, false);
});
VantaRabbit
  • 65
  • 2
  • 10
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

Use like this:

document.getElementsByClassName('test')[0].setAttribute("onclick", myFunction);

Notice the quote is removed from myFunction and the parenthesis is also removed as it would not required because you only need to work this function only when the button is clicked.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • I tried this and still get the same error, but thanks for the suggestion! – Kamui Feb 17 '16 at 04:06
  • 1
    you also need to use the code inside window.load or before the closing of the body tag. – Bhojendra Rauniyar Feb 17 '16 at 04:07
  • let me try that, I will let you know if window.load works. – Kamui Feb 17 '16 at 04:07
  • @BhojendraNepal, `setAttribute` Adds a new attribute or changes the value of an existing attribute on the specified element. Kindly test your solution as I suppose it is not gonna work. It directly adds attributes in the markup much like ` – Rayon Feb 17 '16 at 04:13