Using createElement() outside the function

I'm trying to make a simple ToDo List. The problem I'm currently facing is that when I create the task span outside the function, and the function is called, the value of my input box is given to the span using innnerHTML, and it works fine, but when I click on 'Add Task' button again, it replaces the previous task and gets appended. However if I create the task span inside the function,(so that it is created every time the function is called),it works perfectly fine and gets added next to the previous task. Link to my JSFiddle: https://jsfiddle.net/5mqay9su/1/
Edit fiddle - JSFiddle - Code Playground
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
5 Replies
ἔρως
ἔρως8mo ago
what are you trying to do?
HaiderWaseem
HaiderWaseemOP8mo ago
I know its poorly styled, but I'm just trying to get the tasks added to the Div,one after another,not replacing each other
Wonderbear
Wonderbear8mo ago
The fiddle is kinda broken. I cant even see the input element Ah, I got it now. @HaiderWaseem First of all, you're using the onclick attribute which is dissaproved. And you're using it "wrong" anyway. See, the javascript inside the attribute will be immediately executed, causing the input to dissapear. button.onclick=addTask(); Here you are not assigning the function to the onclick property, but instead you are calling the function and assigning the result which is undefined as you did not use a return statement. And this happens because you reference the exact same span element every time the addTask function is called. You have to create a new span element inside the function.
ἔρως
ἔρως8mo ago
so, this is supposed to create a new span anytime you press the button? if so, what wonderbear said is correct also, DO NOT set the innerHTML property: use textContent or create a text node with document.createTextNode(text) and add it to the span with span.appendChild(node) that property is the devil, and will execute scripts put into it unless you have very good reasons to use innerHTML, don't use it - and showing text is NOT a good reason
HaiderWaseem
HaiderWaseemOP7mo ago
Alright I got that Thank you so much guys @Wonderbear and @ἔρως ❤️
Want results from more Discord servers?
Add your server