0

I am dynamically generating html string and add event to it like below

htmlString = "<a href='#' class='save' onclick='callFunc(" + 4 + ")'>";

I now need to dynamically remove this onclick event and readd again with different Id.

How can i achieve it?

1 Answer 1

1

Assuming that callFunc is a named function, you can nullify element.onclick then add a new event that is bound to your new id:

var newId = 10; 
var saveLink = document.querySelector('.save');
saveLink.onclick = null;
saveLink.onclick = callFunc.bind(saveLink, newId);

Example: https://jsfiddle.net/mqyyf0xu/

Edit: with the new information that you want to increment a count when the user clicks the link, I think you should modify your approach to something like this:

HTML:

<a href="#" class="like" data-likes="0">Likes <span class="like-count">0</span></a>

Javascript:

var likeButton = document.querySelector('.like');

likeButton.onclick = function() {
   var likeCountDisplay = this.querySelector('.like-count');
   var likeCount = parseInt(this.getAttribute('data-likes'), 10) + 1;
   this.setAttribute('data-likes', likeCount);
   likeCountDisplay.textContent = likeCount;
}

Here is an updated fiddle: https://jsfiddle.net/mqyyf0xu/2/

Sign up to request clarification or add additional context in comments.

6 Comments

Is it not possible to change the html and instead of showing onclick="callFunc(4)" it should change to onclick="callFunc(10)"
Not once it has been injected into the DOM
is it possible to change of text in span tag in dom? or that too not possible?
i modified your fiddle. I want to increment value of id on every click but its not happening. I am implementing this likes functionality we have in facebook. It will increase count. jsfiddle.net/mqyyf0xu/1
@Happy I updated my answer to hopefully show you how to accomplish your goal
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.