Help, please solve the problem.

On the page, I would like to hang the event by clicking on those #container that are in the #container block

Suppose an article can be much larger than it is now. For example 200

It is advisable to do without cycles and use pure javascript

  • Have you heard about jQuery? Do not write bicycles. Take advantage of the jQuery ready function : on - ReinRaus pm
  • I heard about jquery and even wrote on it for several years. now I wanted to dig deeper - cyklop77

2 answers 2

You can hang on the container mouseup event, it also works for children. And then check the event target for this event:

 function addEvent(element, eventType, handler){ if(element.addEventListener) element.addEventListener(eventType, handler); else element.attachEvent(eventType, handler); } var c = document.getElementById('container'); addEvent(c, 'mouseup', function(e) { if(e.target.tagName.toLowerCase() == 'article') { e.target.style.backgroundColor = 'red' } }); 

Demo: http://jsfiddle.net/YABB9/1/

UPDATE: Apparently, you can directly hang click : http://jsfiddle.net/YABB9/3/

  • Thank you very much and do not tell me how to make only a selection on the article, which are in #container. that is, just getting a collection of items this way doesn't work var a = getElementById ('container'). getElementsByTagName ('article'); - cyklop77 6:08 pm
  • @Sergey Kalinin: fix on var a = document .getElementById ('container'). GetElementsByTagName ('article'); - Pavel Azanov
 var a = document.getElementById('container').getElementsByTagName('article'); for(var i=0;i<a.length;i++){ a[i].addEventListener( "click" , function(e){ alert(e.target.innerHTML); }, false); } 
  • Thank you all - cyklop77
  • It is better to use delegation (described by @Pavel Azanov) if there are a lot of elements in a collection that will greatly affect performance - cyber_ua