1

I need to clone the onclick event of an element from one link to another.

<a id='foo' onclick='bar'>

I need some javascript or jquery that will return `bar'.

$('#foo').attr('onclick')
    //returns 'undefined'
2
  • 2
    I get the full function returned as a string, not undefined: jsfiddle.net/Z4gAp. What browser are you using? (I'm using Chrome on a Mac) Commented Nov 1, 2011 at 18:26
  • This works fine for me: jsfiddle.net/purmou/73yns @Clive: Mine works just fine, it returns "bar." Commented Nov 1, 2011 at 18:27

2 Answers 2

1

Use the native .getAttribute method of the DOM element.

I have compared .attr('onclick') to [0].getAttribute('onclick'):

  • The jQuery method returned function onclick(event) {bar;} (jQuery version 1.5.2, included by Stack Overflow)
  • The JavaScript method returned "bar"

Test case (copy & paste in console):

$('<a id="foo" onclick="bar">')[0].getAttribute('onclick')
Sign up to request clarification or add additional context in comments.

2 Comments

Really? Both methods gives me bar
@JohnGiotta I tested the code in a console at Stack Overflow, which includes jQuery version 1.5.2 (Get version using $().jquery). See also, this fiddle: jsfiddle.net/3qkJr
1

It returns bar just fine in jQuery 1.6.4, where the prop method returns the full function instead. Solution would be to upgrade your jQuery to the newest version.

http://jsfiddle.net/n9UdN/

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.