SuperMage1
SuperMage1

Reputation: 131

Adding event listener to a newly added DOM element

How do you call an ID that was created through js using a function, but wasn't part of the initial html

var topic1 = document.createElement("div")
document.body.appendChild(topic1)

we tried using an eventlistener

var ff15 = document.getElementById("topic1")
if(ff15){
    ff15.addEventListener("click", response1)
}

but it does not work.

Upvotes: 0

Views: 66

Answers (2)

dork
dork

Reputation: 4608

Add an id to the div if you want to use getElementById.

const topic1 = document.createElement('div');
topic1.id = 'topic1';
document.body.appendChild(topic1);

const item = document.getElementById('topic1');
item.addEventListener('click', () => {
  alert('what');
});

But you can just use topic1 directly if you're not doing anything else.

topic1.addEventListener('click', () => {
  alert('what');
});

Upvotes: 0

Nisarg Shah
Nisarg Shah

Reputation: 14561

You can use the variable topic1 directly to bind an event listener to it. You don't have to get to that element again using document.getElementById.

It could be something as follows:

var topic1 = document.createElement("div");
topic1.innerText = "Some text";
document.body.appendChild(topic1);

topic1.addEventListener("click", function() {
  alert("Clicked");
});

Upvotes: 1

Related Questions