I have a functional code, but would like to improve it for the sake of learning.
I did quite a lot of research and only found a solution using jQuery, but as i'm still a beginer I would like to make in in plain js first. [How do I get HTML button value to pass as a parameter to my javascript?
Basically, I have a list, and I want each entry of this list to call a function with a given parameter, being a natural number.
Among the classic / obstrusive techniques we have:
<li><a href="#" id="0" class="myClass" onclick="return myFunction(0);" >clickMe</a></li>
<li><a href="#" id="1" class="myClass" onclick="return myFunction(1);" >clickMe</a></li>
...
or
<li><a href="javascript:myFunction(0)" id="0" class="myClass">ClickMe</a></li>
<li><a href="javascript:myFunction(1)" id="1" class="myClass">ClickMe</a></li>
...
and
<li><button class="myClass" onClick="return myFunction(0);">ClickMe</button></li>
...
wich indeed call myFunction()
with the parameter set to 0, 1
and so on.
But I've read that it wasn't recomended to do so as
- I'm using the
<a>
tag while I'm not intending to link anywhere. - it mixes HTML and Javascript and that separation of concern is the way to go whenever possible
Then there is the unobstrusive way
<li><button id="0" class="myClass">clickMe</button></li>
completed by
document.getElementById("0").onclick = function (){myFunction()}
This works, but I can't find a way to set my parametter.
If, for instance, I add a value="0"
attribute to my button, or myVar="0"
, I can't use value
as a variable as it isn't declared, and it doesn't set the new value of myVar
, thus myFunction
is called with the wrong parameter being myVar="myVarPreviousValue"
Using GetElementsByClassName : EDIT: updated
Previously we used document.getElementById
, however this may be very inconvinient if the list is long as we would have to create an event listner for every button. In such context, the use of document.getElementsByClassName
seems appropriate.
As pointed by epascarello there's a nice explaination for the use of this method here Document.getElementsByClassName not working.
However this thread can be completed by precising how to get a variable value that is set in the elements of a given class in order to call a function with a given parameter
Bottom line question
How to, unobstrusivelly, call a function with a given parameter when the user click on some html content that have a given class (could be a <li>
, <button>
, <span>
, <div>
as you think is best)
Thank's in advance J.
Edit : updated the question related to the use of getElementsByClassName