Reputation: 495
I have this code:
let button = document.createElement('button');
button.addEventListener('click', create, false);
When I click on the button the function "create" is executed. And my function "create" is:
function create(event) {
event.preventDefault();
console.log(this);
}
The "this" is the DOM of the button.
Now, what I wanted is that after the creation of the button the "create" function was executed automatically, but passed the button's DOM as a parameter. That is, no interaction is required to execute the function. But the result of the "create" function must be the same.
Thank you!
Upvotes: 0
Views: 2962
Reputation: 2684
I'm not sure if this is exactly what you want, but you could use a MutationObserver to call "create" whenever a button is added to the DOM:
function create(event) {
// Runs whenever a button is added to the DOM; this is the button element
console.log(this);
}
// Observe additions of new DOM nodes to the body and its children
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
mutation.addedNodes.forEach(function(node) {
if (node.tagName == 'BUTTON') {
// Call create with the added button as 'this'
create.call(node);
}
});
});
});
// Setup the observer--look only for node additions and removals in body and all child elements
observer.observe(document.body, {childList: true, attributes: false, characterData: false, subtree: true});
var button = document.createElement('button');
document.body.appendChild(button);
Note that the call occurs when the button is added to the DOM, not when the button is created. So if you call document.createElement('button') but do not append it to the DOM, then create will not be called.
Upvotes: 1
Reputation: 8497
I have no idea of what you want to achieve, but here is the code...
With the event listener:
var button = document.createElement('button');
button.innerHTML = 'OK';
document.body.appendChild(button);
button.addEventListener('click', create, false);
function create(event) {
event.preventDefault();
console.log(this);
}
Without the event listener:
var button = document.createElement('button');
button.innerHTML = 'OK';
document.body.appendChild(button);
create.bind(button)();
function create() {
console.log(this);
}
Upvotes: 1