Insert JavaScript via JavaScript

1

I'm studying DOM and I'm having trouble inserting a new <li> and <a> into a given <ul> .

I was able to insert a new <li> using the code below, but I could not succeed in inserting a new <a> into 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>

Follow 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);
}
    
asked by anonymous 06.11.2018 / 03:11

2 answers

2

For the html you're trying to generate, it's still necessary to dynamically create the <a> tag, also through the createElement function. 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>
    
06.11.2018 / 04:03
1

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.
06.11.2018 / 04:04