Creating a new element with javascript

前端 未结 3 1312
时光说笑
时光说笑 2021-01-28 22:50

I\'m trying to create a new li element using a text input. The problem is while the text is appearing, it doesn\'t to create an actual li element that

相关标签:
3条回答
  • 2021-01-28 23:17

    <section>: Used to either group different articles into different purposes or subjects, or to define the different sections of a single article. ref for more info

    You can add the created list element to this <section> <ol> <li> tags at different possible positions as show below.

    var listItem = document.createElement("li"); // Create li element.
    listItem.innerHTML = `taskInput`;
    
    var list = document.getElementById("sectionlist");
    list.appendChild(listItem);
    

    const button = document.getElementById('submit');
    button.addEventListener ("click", () => {
    	var taskInput = document.getElementById('task').value;
    
    	if (taskInput !== '') {
    		var listItem = document.createElement("li"); // Create li element.
    		listItem.innerHTML = taskInput;
    
    		var val = $("input[name='Radios']:checked").val();
        
    		var list = document.getElementById("sectionlist");
    		// https://stackoverflow.com/a/13166249/5081877
    		var listCount = $("#sectionlist li").length;
    		var xpath = '//section/ol/li['+listCount+']';
    		if( val == "Option 1") {
         		list.appendChild(listItem);
    		} else if ( val == "Option 2" ) {
    			var element = document.evaluate(xpath, window.document, null, 9, null ).singleNodeValue;
    			list.insertBefore(listItem, element);
    		} else if ( val == "Option 3" ) {
    			// https://stackoverflow.com/a/2470148/5081877
    			var newElem = new XMLSerializer().serializeToString(listItem);
    			list.insertAdjacentHTML('afterbegin', newElem);
    		}
    	} else {
    		alert("You have to type a task!");
    	}
    });
    body {margin: 2em; font-family: Arial, Helvetica, sans-serif;}
    span {
        /* style this span element so we can display nicely, this stlying is not neccessary */
        margin: 10px 0;
        display: block;
        width: 100%;
        float: left;
    }
    
    input[type="radio"] {
        /* hide the inputs */
        opacity: 0;
    }
    
    /* style your lables/button */
    input[type="radio"] + label {
        /* keep pointer so that you get the little hand showing when you are on a button */
        cursor: pointer;
        /* the following are the styles */
        padding: 4px 10px;
        border: 1px solid #ccc;
        background: #efefef;
        color: #aaa;
        border-radius: 3px;
        text-shadow: 1px 1px 0 rgba(0,0,0,0);
    }
    
    input[type="radio"]:checked + label {
        /* style for the checked/selected state */
        background: #777;
        border: 1px solid #444;
        text-shadow: 1px 1px 0 rgba(0,0,0,0.4);
        color: white;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <body>
    <div id="myFORM">
      <h3>Insert Element into the DOM tree at a specified position.</h3>
      <span>
    	<input id="Radio1" name="Radios" type="radio" value="Option 1" checked="checked">
    	<label for="Radio1">Node.appendChild() - Insert as END Ele.</label>
      </span>
      <span>
    	<input id="Radio2" name="Radios" type="radio" value="Option 2" >
    	<label for="Radio2">Node.insertBefore() - Insert as Last but one Ele.</label>
      </span>
      <span>
    	<input id="Radio3" name="Radios" type="radio" value="Option 3" >
    	<label for="Radio3">Element.insertAdjacentHTML() - Insert as Start Ele.</label>
      </span>
    </div>
    
    <h1>Start your list!</h1>
    <div class="input">
        <input type="text" id="task">
        <button id="submit">Create</button>
    </div>
    
    <section id="list">
      <ol id="sectionlist">
        <li>Default list Data</li>
      </ol>
    </section>
    </body>

    For more information regarding inserting element you can refer my previous post.

    @See

    • Element.insertAdjacentElement()
    • Element.insertAdjacentHTML()
    • Node.appendChild()
    • Node.insertBefore()
    0 讨论(0)
  • 2021-01-28 23:26

    You are appending text you need to append listItem. Check this out:

    Your code:

    list.appendChild(text);
    

    How it should be:

    list.appendChild(listItem);
    

    Best!

    0 讨论(0)
  • 2021-01-28 23:27

    just use <ul> instead of <section> and append to it listeItem and not text.

    const button = document.getElementById('submit');
    
    button.addEventListener ("click", () => {
      var taskInput = document.getElementById('task').value;
      // Creating the text for list item.
      if (taskInput === '') { // Prevents empty list item.
    alert("You have to type a task!");
      } else {
      var listItem = document.createElement("li"); // Create li element.
      var text = document.createTextNode(taskInput); // Create text for list item.
      listItem.appendChild(text); // Append text to li element.
      }
    
      //Add new list item to list
      var list = document.getElementById("list");
      list.appendChild(listItem);
    
    });
    <body>
    <h1>Start your list!</h1>
    <div class="input">
    <input type="text" id="task">
    <button id="submit">Create</button>
    </div>
    <ul id="list">
    </ul>
    </body>

    0 讨论(0)
提交回复
热议问题