Add Onclick Event to Newly Added Element in JavaScript

Add onclick event to newly added element in JavaScript

.onclick should be set to a function instead of a string. Try

elemm.onclick = function() { alert('blah'); };

instead.

How to add onclick to a html element dynamically using javascript

add an eventlistener to the element which has a defined function to call :

elem.addEventListener("click", func, false); //where func is your function name

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

adding onclick event to javascript dynamically created element

Yes, add the onclick to the span:

spanTag.onclick = function() {
this.innerHTML = '';
};

This just clears the content of the span. I wasn't sure exactly what you meant by "erasing".

If you wanted to remove the span entirely, do this:

spanTag.onclick = function() {
this.parentNode.removeChild( this );
};

To remove the row, do this:

spanTag.onclick = function() {
var el = this;
while( (el = el.parentNode) && el.nodeName.toLowerCase() !== 'tr' );

if( el )
el.parentNode.removeChild( el );
};

Or to make it a little clearer perhaps:

spanTag.onclick = function() {
var el = this.parentNode;
while( el ) {
if( el.nodeName.toLowerCase() === 'tr' ) {
el.parentNode.removeChild( el );
break;
}
el = el.parentNode;
}
};

Add onClick event to document.createElement(th)

var newTH = document.createElement('th');
newTH.innerHTML = 'Hello, World!';
newTH.onclick = function () {
this.parentElement.removeChild(this);
};

var table = document.getElementById('content');
table.appendChild(newTH);

Working example: http://jsfiddle.net/23tBM/

You can also just hide with this.style.display = 'none'.

adding onclick event to dynamically added button?

try this:

but.onclick = callJavascriptFunction;

or create the button by wrapping it with another element and use innerHTML:

var span = document.createElement('span');
span.innerHTML = '<button id="but' + inc +'" onclick="callJavascriptFunction()" />';

Attach event to dynamic elements in javascript

This is due to the fact that your element is dynamically created, so it is attached to the DOM later, but your addEventListener call already occurred in the past.
You should use event delegation to handle the event.

document.addEventListener("click", function(e){
const target = e.target.closest("#btnPrepend"); // Or any other selector.

if(target){
// Do something with `target`.
}
});

closest ensures that the click occurred anywhere inside the target element or is the target element itself.
This is useful if, for example, instead of your <input id="btnPrepend"/> you had a <button id="btnPrepend"><i class="icon">+</i> prepend</button> and you clicked the <i class="icon">+</i>.

jQuery makes it easier:

$(document).on("click", "#btnPrepend", function(){
// Do something with `$(this)`.
});

Here is an article about event delegation.



Related Topics



Leave a reply



Submit