You can do this as follows:
function insereLi(texto)
{
// Localiza o elemento <ul> através do seu id, usando getElementById().
var minhaLista = document.getElementById('minhaListaDesordenada');
// Cria um novo elemento <li> no documento.
var newLi = document.createElement('li');
// Informa o texto do novo elemento <li>.
newLi.textContent = texto;
// Insere o novo elemento <li> na lista <ul>.
minhaLista.appendChild(newLi);
}
function insereLiComLink(url, descricao)
{
// Localiza o elemento <ul> através do seu id, usando querySelector().
var minhaLista = document.querySelector('#minhaListaDesordenada');
// Cria um novo elemento <li> no documento.
var newLi = document.createElement('li');
// Informa o texto do novo elemento <li>.
newLi.innerHTML = '<a href ="' + url + '" target = "_blank">' + descricao + '</a>';
// Insere o novo elemento <li> na lista <ul>.
minhaLista.appendChild(newLi);
}
// Testa as duas funções criando mais 3 elementos <li> à lista <ul>.
insereLi('Item dinâmico 1')
insereLiComLink('https://www.jetbrains.com/pycharm/', 'PyCharm')
insereLi('Item dinâmico 3')
<ul id="minhaListaDesordenada">
<li>Item fixo</li>
</ul>
The first function, insereLi()
, inserts a <li>
element with only text, and it uses the document.getElementById()
( documentation ) to find the <ul>
list by its id (which must be unique), and then use the textContent
(documentation ) of the new <li>
element, since we are only inserting text.
The second function, insereLiComLink()
, is given a URL and a description, to mount a <a>
element within the <li>
element. In this role I used document.querySelector()
( documentation ) to find the <ul>
list % by your id, to show an alternative. Here I used the innerHTML
( documentation ) property to add the <a>
element % within the new element <li>
.
The Isac response shows how to add the element <a>
to <li>
using document.createElement()
and document.createTextNode
.
By the searches I did ( What Is A Text Node, Its Uses? ), because I had this doubt and Isac's response made me think about this, some differences between using element.innerHTML
and document.createTextNode()
+ element.appendChild(textNode)
are:
- The
innerHTML
property is newer and the "old" way was to use createTextNode()
;
- For this reason, the
createTextNode()
method may be more compatible with most browsers;
- I thought that using the
createTextNode()
method would be more costly to create a new object, but what the innerHTML
property does in the background is to parse (HTML) and create nodes needed, including text nodes, because the DOM (Document Object Model) " organizes "all of its content as branches of a tree, ending with us , and each node contains objects, so in the background, objects will be created anyway, even for simple text within a tag;
- Just because the% property parses ( parse ) HTML, using it can cause # if values received from the user input are used to populate the property because it can be used for script injection.
-
-