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

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-
  • 635
  • 2
  • 8
  • 21
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