Creating a list of elements traversing an associative array in Ecmascript

Asked

Viewed 42 times

1

I’m trying to create a top menu piece with Ecmascript instead of pure html, but I’m not getting what’s left to add the element.

Code HTML

  <div class="rd-navbar-cell rd-navbar-nav-wrap" id="list">

       <ul class="rd-navbar-nav rd-navbar-nav-default">
             <!-- Queria que os elementos que estão no Array vão parar aqui -->
      </ul>

 </div>

Code Ecmascript:

var listElement = document.querySelector("#list ul")
var listsElement = ['Home',
                    'Cursos',
                    'Promoções',
                    'Eventos',
                    'Blog',
                    'Quem-somos',
                    'Soluções Corporativas',
                    'Parceiros' 
                    ]
var x = listsElement.map(function(item){

    return item;

})

listElement.createElement('li')
listElement.appendChild(x)

I feel like I’m missing something to add or I’m wrong... Could someone explain to me?

1 answer

0


Aluns errors of logic:

  • you have to use the createElement once for each `li``
  • the createElement is a method of document
  • to add content you can use the textContent
  • uses .forEach the .map cannot insert raw

Example:

var listElement = document.querySelector("#list ul")
var listsElement = ['Home',
  'Cursos',
  'Promoções',
  'Eventos',
  'Blog',
  'Quem-somos',
  'Soluções Corporativas',
  'Parceiros'
]
listsElement.forEach(function(tipo) {
  const li = document.createElement('li')
  li.textContent = tipo;
  listElement.appendChild(li)
});
<div class="rd-navbar-cell rd-navbar-nav-wrap" id="list">

  <ul class="rd-navbar-nav rd-navbar-nav-default">
    <!-- Queria que os elementos que estão no Array vão parar aqui -->
  </ul>

</div>

  • Opa @Sergio thanks for the reply, I thought that .map had the same effect as a foreach.

  • 1

    @Rodrigopires more or less... semantically are different, the .map is to create a new array. But in practice both traverse the array.

Browser other questions tagged

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