Doubt with createElement ('div') for id

4

I am developing a portfolio and in the following code you will see that I collect the information from a file .json , until here there is no problem. For those who do not use fetch , I leave the information here.

link

Code:

targetAbout.addEventListener('click', () => {
    document.querySelector('#row').style.display = 'block';
    console.log('Mostrado: ' + targetAbout + hora());
});

// Mostramos contenido por medio de ajax y json.
var respuestaHTML = document.querySelector('#elem');
var tpl = '';

fetch('json/productos.json', {mode: 'no-cors'})
  .then((response) => {
     return response.json()
  })
  .then((category) => {
     category.forEach((elem) => {
        tpl += '<img src="' + elem.thumbnailUrl + '"/>'
         + '<article class="elem-title"><p>' + elem.title + '</p></article>';
     });
     respuestaHTML.innerHTML = tpl;
   }).catch((err) => {
     console.log('Ha fallado: ' + err);
   });

I retrieve the information without problem and shows it in <div> but my question is:

If what I want is that every time I collect the data from a document .json I show it in a div with the same id of the first one? That is, create an element every time you have to show information.

The ID would be elem :

<section id="row">
     <article id="elem">
     </article>
</section>

Should I use createElementById? How do I make it in a div with a certain id?

I would appreciate it in Javascript, not using any frameworks.

    
asked by UnderZero_- 24.06.2016 в 17:30
source

2 answers

5

The createElementById function does not exist, instead use createElement . This does not support the syntax of jquery $('<div id="elem"></div>') , instead the syntax is:

var referencia = document.createElement('tagName');

where tagName is 'div' , 'span' , 'img' , etc.

Then you manipulate the reference and modify its attributes (the id is one of them).

// Creas el elemento
var elem = document.createElement('div');
// Modificas los atributos
elem.id = "elem";
// Lo insertas en el DOM
var parent = document.getElementById('parent');
parent.appendChild(elem);
#parent {
  width: 100px;
  height: 100px;
  padding: 30px;
  background-color: red;
}
#elem {
  background-color: blue;
  width: 100%;
  height: 100%;
}
<div id="parent">
</div>

Having repeated ids is not valid html so I recommend that if you have several of the same type you use classes instead

// Creas el elemento
var elem = document.createElement('div');
// Agregas una clase
elem.classList.add('elem');
// Lo insertas en el DOM
var parent = document.getElementById('parent');
parent.appendChild(elem);
#parent {
  width: 100px;
  height: 100px;
  padding: 30px;
  background-color: red;
}
.elem {
  background-color: blue;
  width: 100%;
  height: 100%;
}
<div id="parent">
</div>

You could delete the previous one before adding a new one if you need it by id

// Buscas el elemento anterior
var old = document.getElementById('elem');
if (old !== null) {
  // Si existe lo eliminas
  old.remove();
}

// Creas el elemento
var elem = document.createElement('div');
// Modificas el id
elem.id = "elem";
// Lo insertas en el DOM
var parent = document.getElementById('parent');
parent.appendChild(elem);
#parent {
  width: 100px;
  height: 100px;
  padding: 30px;
  background-color: red;
}
#elem {
  background-color: blue;
  width: 100%;
  height: 100%;
}
<div id="parent">
  <div id="elem"></div>
</div>

If you manipulate the parent directly you can add several elements using the property innerHTML and you can specify elements and attributes directly in a string of characters.

padre.innerHTML = '<div id="elem"></div>';

This works because the browser parsea this chain and convert it to elements for you. Usually this route is more recommended because of the number of lines of code generated by the creation and manual configuration of elements. In the example I use classes because as I said before you should not have repeated ids.

// Creas el elemento
var parent = document.getElementById('parent');
// Creas una variable que representa el contenido del elemento
var contents = '';
var data = ['e1', 'e2', 'e3'];
for (var i = 0; i < data.length; i++) {
  contents += '<div class="elem">' + data[i] + '</div>';
}
// Reemplazas su contenido completamente
parent.innerHTML = contents;
#parent {
  width: 100px;
  height: 100px;
  padding: 30px;
  background-color: red;
}
.elem {
  background-color: blue;
  margin: 10px;
  height: 100%;
  color: white;
  display: inline;
}
<div id="parent">
</div>
    
answered by 24.06.2016 / 18:02
source
2

I would use with classes instead of ids. If there is a series of elements .elm , I get the one that is empty to show the data there, if not, I create a new one with the same class.

function findEmptyElm() {
  const elms = document.querySelectorAll('.elm');
  elms.foEach((elm)=> {
    if(elm.innerText === '') {
      return elm;
    }
  });
  // si ya todos están disponibles
  const elm = document.createElement('article');
  elm.classList.add('elm');
  document.querySelector('.row').appendChild(elm);
  retun elm;
}

function fetchArticles() {
  // esto de preferencia al principio
  let elm = findEmptyElm();
  /* Tu código */
}
    
answered by 24.06.2016 в 18:05