gs650x
gs650x

Reputation: 405

How to attach single onclick on multiple elements

I have below HTML

<div>
  .. have 10 divs here
</div>

After clicking on each div, I need to get the inner HTML of the div I clicked, so do I have to have add 10 on clicks each on child div, or can this be managed with one on click on parent div?

Upvotes: 0

Views: 127

Answers (4)

Alireza Ahmadi
Alireza Ahmadi

Reputation: 9953

You can set an id for parent element and attach click event to parent instead of each child and then get e.target when clicking:

Here is working sample:

document.querySelector("#parentElement").addEventListener('click', function(e){
    console.log(e.target.innerHTML);
})
<div id="parentElement">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>

</div>

Upvotes: 0

Kirill Savik
Kirill Savik

Reputation: 1278

You can use this code.

const divs = document.querySelectorAll("div div");
[...div].map(val => {
    val.addEventListener("click",() => {console.log(val.innerHTML)});
});


<div>
  <div>a</div>
  <div>b</div>
  <div>c</div>
</div>

Upvotes: 0

jnbm
jnbm

Reputation: 116

You can use addEventListener method (see MDN Web Docs) on parent div.

document.getElementById("parent-div").addEventListener("click",(e)=>{
    console.log(e.target.innerHTML);
})
<div id="parent-div">
    <div>Div 1</div>
    <div>Div 2</div>
    <div>Div 3</div>
    <div>Div 4</div>
    <div>Div 5</div>
</div>

Upvotes: 1

Spectric
Spectric

Reputation: 32022

Use event delegation:

document.addEventListener('click', function(e){
  if(e.target.parentElement.classList.contains("delegate-target"))
    console.log(e.target.innerHTML);
})
<div class="delegate-target">
  <div>1</div>
  <div>2</div>
  <div>3</div>
</div>

Upvotes: 0

Related Questions