addEventListener to an article element in Javascript

浪子不回头ぞ 提交于 2019-11-27 16:29:46

document.getElementsByTagName returns a collection. So you need to iterate over it to add the event listeners. This collection is native DOM nodes collections and not a jquery collection hence you cannot use the addEventListener on the collection.

var articles = document.getElementsByTagName("ARTICLE");
var eventListener = function(){console.log('clicked an articles')}

for(var i=0; i<articles.length; i++){
    articles[i].addEventListener('click', eventListener );
}

Well, you have to check for your latters-cases.

But there is another issue, any code related to DOM elements has to be executed when that certain element is load (or is identified by Javascript Engine). The following event (onload) makes sure when the window is load, and then, it executes the closure assigned to. window.onload = function(){} is what you probably need.

window.onload = function(){
 // call your functions or document event listeners here
}

Also TagName, TagNameNS and ClassName all returns a collection which you have iterate through:

var allDivs = document.getElementsByTagName("div");

for(var i = 0; i < allDivs.length; i++)
{
   allDivs[i].addEventListener();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!