Insert <li> and <a> via Javascript

Asked

Viewed 408 times

1

I’m studying DOM and I’m having trouble inserting a new one <li> and <a> in a certain <ul>.

I managed to insert a new <li> using the code below, but I could not succeed in inserting a new <a> in this new <li>:

I would like to insert the following element into this new <li>:

<a href ="https://www.jetbrains.com/pycharm/" target = "_blank">PyCharm</a>

Follows the code:

function insereLi(){

    //Adicionar um novo elemento a uma arvore
    //Criar um novo elemento e o armazena em uma variavel
    var newEl = document.createElement('li');

    //Criar um nó de texto e armazenar em uma variável
    var newText = document.createTextNode('Pycharm');

    //Anexar novo nó de texto ao elemento criado
    newEl.appendChild(newText);

    // Localiza a posição onde o elemento deve ser posicionado
    var position = document.getElementsByTagName('ul')[1];

    //insere o novo elemento em sua posição
    position.appendChild(newEl);
}

2 answers

2


For the html you are trying to generate, you need to dynamically create the tag <a>, also through the function createElement. Then the attributes of this <a> are placed using setAttribute.

Example:

function insereLi(){
    var newEl = document.createElement('li');
    var newA = document.createElement('a'); //a tag <a> que faltava
    var newText = document.createTextNode('Pycharm');
    var position = document.getElementsByTagName('ul')[0];
    
    //os atributos do <a>
    newA.setAttribute("href", "https://www.jetbrains.com/pycharm/");
    newA.setAttribute("target", "_blank");

    newA.appendChild(newText); //colocar o texto no <a>
    newEl.appendChild(newA); //e o <a> dentro do <li>
    position.appendChild(newEl);
}

document.querySelector("button").addEventListener("click", insereLi);
<button>Insere Li</button><br><br>

Lista
<ul>
  <li>Um item</li>
</ul>

  • I was wondering why use document.createTextNode() instead of simply using the property innerHTML, since it seems more laborious and even more costly thinking logically (more a created object), and I have now seen this answer: Is there any major Difference between innerHTML and using createTextNode to Fill a span?. I had thought to put in my reply a version that also added the tag <a> using the method createElement(), but I didn’t, and you answered almost together and did so. I voted in your reply! ;-)

  • 1

    @Pedrogaspar innerHTML is of course simpler but I chose to keep the style that AP had. Yet there is one or two subtle differences that may or may not be relevant, such as JS injection.

  • Oh yes, I also thought of using the createTextNode to follow the same style, only I chose to show a different way, however I wanted to show the form with createTextNode also, but fortunately you have met that need! I can add this information about the difference between the two in my reply or you will add in your?

  • @Pedrogaspar Just as I later thought I’d put an alternative with innerHTML but then when I noticed there was already your answer with this alternative :D. Feel free to put the differences, which is something that enriches the answer.

  • Good morning @Isac. I successfully implemented your collaboration on my first study page. https://maxwneto.github.io/ Thanks for your help.

1

You can do it this way:

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 an element <li> only with text, and she uses the method document.getElementById() (documentation) to find the list <ul> by your id (which should be unique), and then use the property textContent (documentation) of the new element <li>, since we are only inserting text.

Already the second function, insereLiComLink(), receives a URL and a description to mount an element <a> within the element <li>. In this role I used the document.querySelector() (documentation) to find the list <ul> by your id, to show an alternative. Here I used the property innerHTML (documentation) to add the element <a> within the new element <li>.

To isac response shows how to add the element <a> at the <li> using document.createElement() and document.createTextNode.

For the research I’ve done (What Is A Text Node, Its Uses?), because I had this doubt and the answer from Isac made me think about it, some differences between using element.innerHTML and document.createTextNode()+element.appendChild(textNode) sane:

  • The estate innerHTML is more recent and the "old" way was to use the createTextNode();
  • That is why the method createTextNode() may be more compatible with most browsers;
  • I thought using the method createTextNode() would be more costly to create a new object, but what the property innerHTML in the background is to analyze (parse) HTML and create the necessary nodes, including text nodes, because the GIFT (Document Object Model) "organizes" all its contents as branches of a tree, ending in us, and each node contains objects, so at the bottom, objects will be created anyway, even for a simple text within a tag;
  • Precisely because of the fact of the property innerHTML analyze (parse) the HTML, the use of it can cause a security risk, if incoming user input values are used to populate the property, because it can be used for script injection.
  • Good morning @Pedro Gaspar. Thank you very much for your cooperation. I was able to understand its solution but kept in the code the solution of Isac because it was what I had thought but I could not evolve with the solution. But it is very good to have a second line of reasoning. Hugs.

  • I’m glad you helped Max! But, here the best way to thank for an answer is to mark it as accepted (by clicking on the "visa sign", just below the down arrow), see this page: What should I do if someone answers my question? and Why it is important to vote?. Then accept the answer of the Isac, please (in addition to everything you still earn 2 points for it). Also take the opportunity to visit the welcome page of the site.

  • Thanks again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.