1

I'm new at programming so I may have made some, even obvious mistakes.

Now I'm working on a little script where I'd like to add some new content in a paragraph after a div I made at 2 conditions ( if, else ).

if something is written than put the text into a div and the console.

else create a <p> element and write that text is needed after the div element.

I set the code but the console on Chrome says that

DivI.insertAfter(p, Div) is not a function

at onclick(HTML) property inside the button.

Even DivT.appendChild(text) is not a function.

Following the guide given by Brackets, I, inside the if, created a new variable DivT and appended the text(createTextNode) inside DivT.

Inside the else I created a new element <p>, inserted text inside, created 2 variables in order to use the method insertAfter as it was written on the guide.

One for telling where to append and the other to tell after which element putting the <p> element.

I can't make it work.

Here is the code.

HTML

           <input type="text" id="scrivimi">

           <button type="button" onloadend="Cliccando()" 
           onclick="Cliccando()">
            Clicca 
           </button>

    <div id="Div"></div>

Apart from a title these are the only elements in the page.

Javascript

        function Cliccando() {
          var testo2 = document.getElementById('scrivimi').value;
            if ( testo2 != '')
                {
                    alert('js qualcosa scritto');
                    console.log(testo2);
                    var DivT = document.getElementsByTagName('div');
                    var DelTesto = document.createTextNode(testo2);
                    DivT.appendChild(DelTesto);
                   }
                else {
                      alert (' js vuoto');
                      var p = document.createElement("p");
                      var Contenuto = document.createTextNode('Scrivi del testo');
                p.appendChild(Contenuto);
                var DivI= document.getElementById('Div');
                var Div = document.getElementById('Div');
                DivI.insertAfter(p, Div);

            }

     }
AndrewL64
  • 15,794
  • 8
  • 47
  • 79
  • JS has an `insertBefore` but not an `insertAfter`. See [this question](https://stackoverflow.com/q/4793604/1810460) for a workaround – Hamms May 24 '18 at 22:25
  • I would create div in html and provide display - block or none on JavaScript function as per needed. – A J May 24 '18 at 22:26
  • Also, the reason you're getting an error with `appendChild` is that [`getElementsByTagName` returns an HTMLCollection](https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName) not just a single Node. I would recommend instead using `getElementById` – Hamms May 24 '18 at 22:26
  • Problem solved, thank you! – Vittorio D'angiolino May 25 '18 at 13:18

0 Answers0