I am new to JavaScript and StackOverflow. I am trying to extract all he button elements from a page and then set an onclick attribute to them I have tried the following but it does not seem to work any help would be appreciated.
var btn = [];
for (var i=-1; i<btn.length; i++)
{
btn[i] = this.document.getElementsByTagName("button")
.setAttribute("onClick","btnClick()");
}
console.log("array length " + btn.length);
console.log(btn);
In the console I get:
script.js:13 Uncaught TypeError: this.document.getElementsByTagName(...)
.setAttribute is not a function at script.js:13
(anonymous) @ script.js:13
I have tried a number of different things, if I remove the .setAttribute
from the code I get:
script.js:15 array length 0
script.js:16
[-1: HTMLCollection(13)]
-1: HTMLCollection(13)
board:button#board.btn
edCourse:button#edCourse.btnGray1
edModule:button#edModule.btnGray1
edStudent:button#edStudent.btnGray1
entCourse:button#entCourse.btnGray
entModule:button#entModule.btnGray
entStudent:button#entStudent.btnGray
length:13
resultLst:button#resultLst.btn
sap:button#sap.btn
trans:button#trans.btn
vwCourse:button#vwCourse.btnGray
vwModule:button#vwModule.btnGray
vwStudent:button#vwStudent.btnGray
0:button#entStudent.btnGray
1:button#entCourse.btnGray
2:button#entModule.btnGray
3:button#edStudent.btnGray1
4:button#edCourse.btnGray1
5:button#edModule.btnGray1
6:button#vwStudent.btnGray
7:button#vwCourse.btnGray
8:button#vwModule.btnGray
9:button#sap.btn
10:button#board.btn
11:button#trans.btn
12:button#resultLst.btn
__proto__:HTMLCollection
length:0
__proto__:Array(0)
Please help, sorry if this question has been asked before, but I couldn't find an answer.