Let's say I have the following HTML lines calling a JS function.
<h3>
<span class="my-class" onclick="myFunc()">one</span>
<span class="my-class" onclick="myFunc()">two</span>
<span class="my-class" onclick="myFunc()">three</span>
<span class="my-class" onclick="myFunc()">four</span>
</h3>
How can I call myFunc()
right from the script without having to repeat myself by writing onclick="myFunc()"
so many times in the HTML file?
Thanks in advance!
Use codes below :
var elements= document.getElementsByClassName("my-class");
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', myFunc, false);
}
I learnt what I'm coming to share in a tutorial and it works for me.
function myFunc()
{
console.log('Body of myFunc');
}
var span_list = document.getElementsByClassName('my-class');
for(this_span = 0; this_span < span_list.length; this_span++)
{
span_list[this_span].addEventListener('click', myFunc);
}
With this method, you have access to do something peculiar to a specific element by using the ' getAttribute() ' method on one of your class.
Hope this helps.
You can assign the listener to multiple elements by looping through the results of a method such as Document.querySelectorAll()
.
Furthermore, you can also reduce repitition in your markup by assigning the class once to the parent element. In this case, it would be the <h3>
element. Then you modify your query selector accordingly.
Here's an example where I've assigned an id
to each <span>
element to facilitate identifying which element was clicked:
function myFunc() { console.log(`myFunc() called for ${this.id}`); } for (const e of document.querySelectorAll('h3.my-class > span')) { e.addEventListener('click', myFunc, false); }
<h3 class="my-class"> <span id="one">one</span> <span id="two">two</span> <span id="three">three</span> <span id="four">four</span> </h3>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.