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);
}
}