0

When I run this Javascript code

var anchor = document.createElement("a");
anchor.style = "cursor:pointer;color:blue;";
 anchor.onclick = "this.parentNode.parentNode.removeChild(this.parentNode);";
 anchor.innerHTML = "remove";
 div.appendChild(anchor);

My anchor is created as <a style="cursor: pointer; color: blue;">remove</a> The onclick attribute is missing and the onclick function does not work.

Can I fix it?

1
  • Note that setting an element property doesn't necessarily affect the related attribute and vice versa. Commented Jan 6, 2015 at 2:30

1 Answer 1

2

You are setting it to a string and it does not actually set the attribute. Use a closure.

anchor.onclick = function() { this.parentNode.parentNode.removeChild(this.parentNode); };

ideally you would be using addEventListener

anchor.addEventListener("click", function(){ this.parentNode.parentNode.removeChild(this.parentNode); }, false);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Only the solution with addEventListener works. But it's good to see what does not work as well.

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.