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?
onclickattribute 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?.insertBefore()does the opposite of what you seem to expect. It's going to put the matchedtitlebefore the newa, which isn't in the DOM according to your example..insertBefore(), which would behave like the DOM's.append()method since you're not passing a second argument.divwith id "title", but after the text that's already there on thediv. I'd be complaining about that if it didn't work, now wouldn't I? What second argument are you talking about?