Bind Event To Dynamically Created Html Elements With Vanilla Javascript [no Jquery]
I need to attach an event to a dynamically created element. With jQuery I can archive this by using the following code: $('body').on('click', '.my-element', function() {}); And if
Solution 1:
A pure JavaScript version of your jQuery example
$("body").on("click", ".my-element", function() {});
would be:
document.body.addEventListener("click", function (e) {
if (e.target &&
e.target.classList.contains("my-element")) {
// handle event here
}
});
See example below.
constaddTestElements = () => {
var el = document.createElement("p"),
node = document.createTextNode("Test element, class 'my-element'");
el.classList.add("my-element");
el.appendChild(node);
document.body.appendChild(el);
el = document.createElement("p");
node = document.createTextNode("Test element, class 'test'");
el.classList.add("test");
el.appendChild(node);
document.body.appendChild(el);
}
document.getElementById("add").addEventListener("click", addTestElements);
document.body.addEventListener("click", function (e) {
if (e.target &&
e.target.classList.contains("my-element")) {
console.clear();
console.log("An element with class 'my-element' was clicked.")
e.target.style.fontWeight = e.target.style.fontWeight === "bold" ? "normal" : "bold";
}
});
<buttonid="add">Add element</button>
Post a Comment for "Bind Event To Dynamically Created Html Elements With Vanilla Javascript [no Jquery]"