0

How can I use jQuery to replace part of the onclick property / attribute? In the example below I would like to replace delete_image with do_delete_image:

Sample HTML

<a href="#" onclick="delete_image(1234)" >Delete Image</a>

My Attempt

jQuery('a').each(function(){
    var action = $(this).prop('onclick').replace('delete_image','do_delete_image');
    $(this).prop('onclick',action);
});

Error

Google chrome is throwing this error:

TypeError: Object function onclick(event) { delete_image(1234);return false; } has no method 'replace'

How can I make this work? ps: This is a bookmarklet set to work with someone else's code.

3 Answers 3

2

onclick is a property representing the function that handles the click event. To get and set the actual content, use attr instead of prop.

Alternatively, consider replacing delete_image with do_delete_image, for example:

window.delete_image = window.do_delete_image;

You can combine this with closures if you need to wrap the original function.

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

1 Comment

not a method to edit the attribute but a slick way to achieve what i wanted. thanks so much! +1
0

use $(this).unbind() to clear handlers on that element and then add new one

Comments

0

As of jQuery 1.7, this should work...

jQuery('a').each(function(){
    $(this).off('click')
        .on('click', do_delete_image);
});

Comments

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.