0

I have a function that adds an anchor/hyperlink to an element with ID "title".

    var a = document.createElement('a');
    a.innerHTML = "Link text";
    a.href = "http://example.com";
    a.style.fontSize = "14px";
    a.style.fontWeight = "normal";
    a.onclick = function() { alert('OK'); };

    // now add anchor to DOM
    $('title').insertBefore(a);

The link is added successfully to the DOM and its style attributes are set just fine, but not the onclick. Viz., this is what I get:

<a href="http://example.com" style="font-size: 14px; font-weight: normal;">Link text</a>

Why isn't the onclick added? What am I doing wrong?

10
  • 1
    Setting the onclick attribute in JS won't actually display it in the markup. Did you actually click on your link to verify that the hander isn't firing? Commented Nov 6, 2013 at 19:25
  • 1
    FYI, if that's jQuery, the .insertBefore() does the opposite of what you seem to expect. It's going to put the matched title before the new a, which isn't in the DOM according to your example. Commented Nov 6, 2013 at 19:28
  • @Mathletics, you'd think I'd have done that, wouldn't you? D'oh! Commented Nov 6, 2013 at 19:32
  • ...maybe you're using the DOM .insertBefore(), which would behave like the DOM's .append() method since you're not passing a second argument. Commented Nov 6, 2013 at 19:32
  • @BlueSkies, what actually happens is what I want: the anchor appears within the div with id "title", but after the text that's already there on the div. I'd be complaining about that if it didn't work, now wouldn't I? What second argument are you talking about? Commented Nov 6, 2013 at 19:35

2 Answers 2

3

The onclick handler should work, even if it's not displayed as an attribute. If you really want to add the onclick attribute inside the HTML, use setAttribute.

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

1 Comment

If you want to see it in the html, use a.onclick="alert('OK')". But while this works (and use the usual way to do it years ago), it'S not really pretty and doesn'T have any advatages (well, despite the onclick attribute showing up in the DOM).
2

It is being added. It just isn't showing up in the HTML. It is being added virtually.

When you use onclick = function it does a virtual bind instead of actually adding the attribute.

You would need to use setAttribute("onclick","alert('ok');") if you need it to appear in the HTML (I'm not sure why you would need this though).

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.