7

How can I get the ID of a child node of an element when the parent node has many child nodes?

<div id="parentID">
    <div id="id_1"></div>
    <div id="id_2"></div>
    <div id="id_3"></div>
    ...
    <div id="id_n"></div>
</div>

In the above code example, how can I get the ID of any child node when the user clicks it?

EugenSunic
  • 13,162
  • 13
  • 64
  • 86

3 Answers3

4

Assign an eventListener to the parent element and when clicking on the child element retrieve their id attribute. Here is a code sample:

document.getElementById('parentID').addEventListener('click', (e) => {
  console.log(e.target.id)
})
<div id="parentID">
  <div id="id_1">id1</div>
  <div id="id_2">id2</div>
  <div id="id_3">id3</div>

  <div id="id_n">idn</div>
</div>
Muhammad Zeeshan
  • 4,608
  • 4
  • 15
  • 41
EugenSunic
  • 13,162
  • 13
  • 64
  • 86
-1

Sure, events in the dom propagate and move from child to parent evnetually.

You can add a single event listener and check its target property. This technique of adding a single event listener and routing based on children is called event delegation.

document.querySelector("#parentID").addEventListener('click', (e) => {
  // e is an event object
  // e.target; is whomever was actually clicked
  if (e.target.id === 'id_1') {
    // do something specific.
  }
});

Note that in general having sequential IDs in your code is a code smell indicating bad separation of concerns. So make sure you know it's the right thing to do before doing it.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
-1

you can try this.

function byid( e ){ return document.getElementById( e ); }
var id1 = byid( "id_1" ),
    id2 = byid( "id_2" ),
    id3 = byid( "id_3" ),
    id4 = byid( "id_4" );
[id1,id2,id3,id4].forEach( e => {
    e.addEventListener( "click",getId );
    function getid( e ){
        alert( e.getAttribute( "id" ) );
    }
} );