mike watawski
mike watawski

Reputation: 90

proper way to create element in javascript

here's how i create element

var a = document.createElement("a");
a.setAttribute("id","remove");
a.setAttribute("uk-icon","icon: trash");

when i inspect

enter image description here

i want to get a tag but it only gives icon

document.addEventListener('click', function(e){
    console.log(e.target);
});

enter image description here

what is the correct way on creating element?

Upvotes: 0

Views: 65

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65853

Your question/problem is unclear. document.createElement() is the correct way to create an element (although an a element does not have a uk-icon attribute). The inspect code you shared clearly shows that you made a new element. It looks like you've then placed an SVG element within the a element and that's what you'll see on the page. And, since that's what you see, then that's what you are clicking on. Instead of document.addEventListener(), use document.querySelector("#remove").addEventListener() to react to the a being clicked.

Upvotes: 1

Related Questions