2

Why the difference?

document.getElementById('click').onclick = a.replaceChild(c,b) --- replaces the element without me clicking the button

but onclick="a.replaceChild(c,b)" --- replaces the element only after the button is clicked

<div id="container">
<p id="welcome">no greetings yet</p>
<p id="products">oreo ice-cream</p>
</div>

<button id="click" **onclick="a.replaceChild(c,b)"**>CHANGE</button>

    <script>

        var a = document.getElementById('container');

        var b = document.getElementById('welcome');

        var c = document.createElement('h2');
        c.id = 'new';
        c.innerHTML = "WELCOME";

        **document.getElementById('click').onclick = a.replaceChild(c,b);**

    </script>
Ash
  • 21
  • 1
  • 1
    because you call the method and what it returns is assigned to the event listener... – epascarello Dec 08 '17 at 04:25
  • What is `onclick="a.replaceChild(c,b)` here? – brk Dec 08 '17 at 04:26
  • `replaceChild()` is a javascript function called on container div (`a`). It replace `b` with `c` that means `

    ..

    ` replaced by `

    ...

    `
    – Anant Kumar Singh Dec 08 '17 at 04:27
  • Possible duplicate of [Html onclick attribute vs script's onclick event listener](https://stackoverflow.com/questions/42819916/html-onclick-attribute-vs-scripts-onclick-event-listener) – Anant Kumar Singh Dec 08 '17 at 04:31
  • Does this answer your question? [addEventListener vs onclick](https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick) – leonheess Jan 20 '20 at 15:37

2 Answers2

0

You don't include the parentheses: you'd assign a parameterless function like document.getElementById('foo')=bar;, not like bar().

The way you're assigning it now actually runs it, which means you're assigning the return value from that function, not its name.

The parameters make it slightly trickier than just naming the function without parentheses.

document.getElementById("click").onclick = function(c, b){return a.replacechild(c,b);}

This'll do what you're looking for. JSFiddle

jQuery's .click() is a good alternative if you're interested in solutions that aren't pure basic javascript. Another may be adding an event listener instead in some cases.

HB-
  • 595
  • 2
  • 6
  • 19
0

"document.getElementById('click').onclick" is just returning the state onClick whenever that line runs. Probably at page load time.

What you want to do is add an event listener which will listen for a change in the .onclick state. Then call your function with that.

This is what the onClick attribute is doing. Its generally advisable to use an event listener so you cna clearly separate your content from your JS logic.

Kirby
  • 155
  • 7