Home > Blockchain >  how to add an elemnt with text inside in Javascipt Dom
how to add an elemnt with text inside in Javascipt Dom

Time:11-08

I work currently on my todo list.

I manged to get the text value from my input but i dont now how to add and element with the text value inside the text area. I want to add the text from my input inside the textarea in the undordered list.

Green is the input field and i want to get it from there in the white fieldenter image description here

//query select to get button

let btn = document.querySelector('.add');
// selector to selct undorder list inside todotex
const ul = document.querySelector('.list');
//selector for input
const input = document.querySelector('input');

// eventlistner by button clicked

btn.addEventListener('click', function() {
  var txt = input.value;
  let li = document.createElement('li').innerHTML(txt);
  ul.append(li);
});
<div >
  <div >TODO List</div>
  <div ></div>
  <ul >

  </ul>
  <div >
    <button  type="button">   </button>
    <input type="text"  placeholder="add todo"></input>
  </div>
</div>

CodePudding user response:

As comment by @CBroe. Replace innerHTML(txt);to innerHTML = txt;

CodePudding user response:

https://jsfiddle.net/Memorynotfound/obhq8x50/

I found this JSFiddle that might help. Google is your best friend.

This guide explains it: https://memorynotfound.com/dynamically-addremove-items-list-javascript/

function addItem(){
    var ul = document.getElementById("dynamic-list");
  var candidate = document.getElementById("candidate");
  var li = document.createElement("li");
  li.setAttribute('id',candidate.value);
  li.appendChild(document.createTextNode(candidate.value));
  ul.appendChild(li);
}

function removeItem(){
    var ul = document.getElementById("dynamic-list");
  var candidate = document.getElementById("candidate");
  var item = document.getElementById(candidate.value);
  ul.removeChild(item);
}
<ul id="dynamic-list"></ul>

<input type="text" id="candidate"/>
<button onclick="addItem()">add item</button>
<button onclick="removeItem()">remove item</button>

CodePudding user response:

As @CBroe stated, innerHTML is a property and not a method. Instead of going like this

let li = document.createElement("li").innerHTML(txt);
ul.append(li);

Use:

let li = document.createElement("li");
li.innerHTML = txt;
ul.append(li);
  • Related