How to add click event to an element?

前端 未结 4 769

I would like to add a click event in plain JavaScript (without using jQuery) to an element like this, so I don\'t have an id but a class:



        
4条回答
  •  孤街浪徒
    2020-11-27 08:49

    There can be several ways of doing this.

    One is you add the click event right in the anchor

    as: Yummy

    The other way can be using document.getElementsByTagName('a') you can get reference to all the href's as array then you can chose that particular href and add click event to it.

    like: document.getElementsByTagName('a')[0].click = function(){ }

    here 0 is just symbolic if u know the exact place in array you can give that index.

    The third way can be you can write a custom. document.getElementsByClassName function in javascript and use it similiarly. You can find a number of implementations of getElementsByClassName by searching google.

    look at http://robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/ one of the implementation.

提交回复
热议问题