0

i got blocks like these:

<div class="listener" id="123">
<h1>Title</h1>Some text...
<div class="container"></div>
</div>

<br>

<div class="listener" id="456">
<h1>Title</h1>Some text...
<div class="container"></div>
</div>

CSS:

.listener{width:500px;background:red;border:1px solid black}

JavaScript:

document.getElementByClassName("listener").addEventListener("click", function()

{

// get the id of the DIV
// put content inside the class=container inside the DIV with innerHTML

});

What should happen?

After clicking in one of those boxes:

  • call the function
  • get the ID of the clicked DIV
  • put some content inside the DIV (DIV with class=container)

Please NO solution with <a> or jQuery.

Any idea? Thanks!

I have a Fiddle here: https://jsfiddle.net/wwp9jk8t/

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Chama
  • 189
  • 1
  • 3
  • 11
  • See that SO question: http://stackoverflow.com/questions/3219758/detect-changes-in-the-dom – roland Mar 06 '16 at 15:56
  • @roland — You've misread the question. It is asking how to change the DOM when a click event is received, not what event is fired when the DOM is changed. – Quentin Mar 06 '16 at 15:57
  • You have two problems: 1. It's getElementsByClassName, not getElementByClassName and 2. you can't call addEventListener to a node list. You must select a node in the node list and then you can call addEventListener. – Scott Marcus Mar 06 '16 at 16:05

1 Answers1

1

document.getElementByClassName("listener") will return nodelist not a DOM element and you can not bind click event to over array-like NodeList. Use [].forEach.call/for-loop to iterate all the elements in nodeList and apply adeventListener to every element.

Also note typo getElementByClassName, it should be getElementsByClassName(plural)

Try this:

[].forEach.call(document.getElementsByClassName("listener"), function(elem) {
  elem.addEventListener("click", function() {
    alert(this.id);//to get the id attribute of the clicked element..    
    this.getElementsByClassName("container")[0].innerHTML = "Hello World";
  });
})
.listener {
  width: 500px;
  background: red;
  border: 1px solid black
}
<div class="listener" id="123">
  <h1>Title</h1>Some text...
  <div class="container"></div>
</div>

<br>

<div class="listener" id="456">
  <h1>Title</h1>Some text...
  <div class="container"></div>
</div>
Community
  • 1
  • 1
Rayon
  • 36,219
  • 4
  • 49
  • 76
  • This is great! Is it possible to get the ID of the DIV too? Because it should load content via Ajax ('getdata.php?id=....') – Chama Mar 06 '16 at 16:23
  • Works great! I have to put the JS-code below the elements, right? The script doesn't work if reload new div-boxes with ids... any idea how to refresh the index of the elements in the dom? – Chama Mar 06 '16 at 17:30
  • Script should be placed after HTML before `

    ` or wrap in `DOMContentLoaded`..For dynamically added elements, you will have to bind event again..

    – Rayon Mar 06 '16 at 18:15