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
let div = document.createElement('DIV');
div.classList.add(".whatever");
div.addEventListener('click', function() {
console.log('dynamic elements')
});
document.body.appendChild(div);
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') }
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/
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>
console.log()
if the ev.target
, ie the clicked element, is of class "el".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.