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.
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>
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');
}
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('');
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.
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.
©2020 All rights reserved.