Javascript/jQuery - How do I obtain name of the class of clicked element?

前端 未结 6 1557
礼貌的吻别
礼貌的吻别 2020-12-16 00:27

I googled and googled and I concluded that it\'s very hard to get answer on my own.

I am trying to use jquery or JavaScript to get a property of clicked element. I c

6条回答
  •  自闭症患者
    2020-12-16 00:59

    You can use element.className.split(/\s+/); to get you an array of class names, remember elements can have more than one class.

    Then you can iterate all of them and find the one you want.

    window.onclick = function(e) {
        var classList = e.srcElement.className.split(/\s+/);
        for (i = 0; i < classList.length; i++) {
           if (classList[i] === 'someClass') {
             //do something
           }
        }
    }
    

    jQuery does not really help you here but if you must

    $(document).click(function(){
        var classList =$(this).attr('class').split(/\s+/);
        $.each( classList, function(index, item){
            if (item==='someClass') {
               //do something
            }
        });
    });
    

提交回复
热议问题