Javascript to create an li and append to an ol

余生颓废 提交于 2020-01-30 02:44:15

问题


I'm trying to use JavaScript to create an li and append it to an existing ol. The code I am using is

<ol id=summaryOL>
</ol>

function change(txt) {
var x=document.getElementById("summaryOL");
newLI = document.createElementNS(null,"li");
newText = document.createTextNode(txt);
newLI.appendChild(newText);
x.appendChild(newLI);
}

change("this is the first change");
change("this is the second change");

These should look like:

1. this is ...
2. this is ...

But look like:

this is the first changethis is the second change

I have created a fiddle at: fiddle . Thanks for any help.


回答1:


Here is an example - jsfiddle

$(function() {
    var change = function( txt ) {
        $("#summaryOL").append( '<li>' + txt + '</li>' );
    };

    change("this is the first change");
    change("this is the second change");
});

To use jquery, put below code inside of <head></head>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>



回答2:


Try Below. It worked for me. Remove null from

newLI = document.createElementNS(null,"li");

function change(txt) {

    var x=document.getElementById("summaryOL");
    newLI = document.createElement("li");

    newText = document.createTextNode(txt);
    newLI.appendChild(newText);
    x.appendChild(newLI);
    alert('DONE');

    }



回答3:


Your fiddle is not relevant to your question...

In your fiddle, it works fine but you should never have an ID that starts with a number.

In your question, createElementNS is pointless - just use createElement('li') instead.




回答4:


Just looking and this and can't believe it hasn't been answered without jQuery, so just putting it here. In Vanilla JS, you can do:

const ol = document.querySelector("#summaryOL");
const li = document.createElement('li');
const text = document.createTextNode(txt);
li.appendChild(text);
ol.appendChild(li);

or alternatively, by modifying innerHTML of ol node directly:

document.querySelector('#summaryOL').innerHTML =
  changes
    .map(txt => `<li>${txt}</li>`)
    .join('');



回答5:


If you are using jQuery, you can try this:

var item= "<li>" + "some info" + "</li>" ;
$("#items").html($("#items").html() + var);

and obviously appending to the list is another solution.



来源:https://stackoverflow.com/questions/9107541/javascript-to-create-an-li-and-append-to-an-ol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!