Uriel
Uriel

Reputation: 206

Add click event on a dynamically created element in Javascript

I am trying to add a click event on an element which i create dynamically in Vanilla JS. With jquery its super simple all i would do is

$(document).on('click','.el', function() {
    //somecode 
})

However with Vanilla JS (because i'm using react) i can't do the same thing. I've tried adding the dynamic element as an argument just like i would in jquery but no money.

I'm sure it can be done just not the way i'm thinking. Any ideas?

I tried

let div = document.createElement('DIV')
div.classList.add('el')
document.addEventListener('click','.el', function() {
    //some code
})

I also tried

document.addEventListener('click',div, function() {
    //some code
})

None of these methods worked

Upvotes: 0

Views: 4753

Answers (4)

Carsten Massmann
Carsten Massmann

Reputation: 28196

You can do something like the following:

const d=document.getElementById("container");
document.addEventListener('click', function(ev) {
  if (ev.target?.classList.contains('el')) { 
   console.log("My .el element was clicked!");
   ev.target.classList.contains("segundo") && 
   (d.innerHTML+='<p class="el">another clickable paragraph</>');
  }
})
<div id="container"><h2>Something unclickable</h2>
<p class="el primero">A clickable paragraph!</p>
<p class="otro primero">something unclickable again ...</p>
<button class="el segundo">add clickable element</button>
</div>
The event handler is attached to the document itself but will only fire the console.log() if the ev.target, i. e. the clicked element, is of class "el".

Upvotes: 1

Khushboo
Khushboo

Reputation: 94

i think what you are missing is appending the element you created to your DOM. have a look at this:

var createDiv = function() {
  let div = document.createElement('DIV');
  div.id = 'el';
  div.innerHTML = '<b>hey</b>';
  div.classList.add('styles');
  document.body.appendChild(div);
  div.addEventListener('click', function() {
    alert('Look here');
  })
};

here's a fiddle so you can playaround: https://jsfiddle.net/khushboo097/e6wrLnj9/32/

Upvotes: 1

m0shiur
m0shiur

Reputation: 46

let div = document.createElement('DIV');
div.classList.add(".whatever");
div.addEventListener('click', function() {
    console.log('dynamic elements')
});
document.body.appendChild(div);

https://jsfiddle.net/yu1kchLf/

Upvotes: 3

Always Helping
Always Helping

Reputation: 14570

You could simply use and onclick function and just call it as variable from your dynamically added elements.

Live Demo

//Create function
let button = document.createElement('button');
button.classList.add("myBtn");
button.innerText = 'Click Me';
button.onclick = myFunction //assign a function as onclick attr
document.body.appendChild(button);


//Call function
function myFunction() {
  console.log('I am being called from dynamically created button')
}

Upvotes: 1

Related Questions