Home > other >  how to add innerHTML in another row?
how to add innerHTML in another row?

Time:05-31

I am trying to add a list of users under the "participants". My current code add the elements next to the work participants.

    showname.innerHTML = `<h4>participants:</h4>`   '<ul>'   users.map(function (user) {
        return '<li>'   user   '</li>';
    }).join('')   '</ul>';

So I like something like this:

participants:

-user1
-user2
-user3

but currently it is:

participants: user1 user2 user3

CodePudding user response:

There's not much wrong in your code unless you didn't assign selector properly. If you have a div with class container, here is what you should do without changing your code.

const showname = document.querySelector('.container');
const users = ['Solomon', 'Abebe', 'Sara'];
showname.innerHTML = '<h4>participants:</h4>'   '<ul>'   users.map(function (user) {
        return '<li>'   user   '</li>';
}).join('')   '</ul>';

The other option is to create html elements and append them on the existing

const containerBox = document.createElement('div');
containerBox.classList.add = 'container-box';
showname.appendChild(containerBox);
containerBox.innerHTML = '<h4>participants:</h4>'   '<ul>'   users.map(function (user) {
        return '<li>'   user   '</li>';
}).join('')   '</ul>';

As I said, there's not much you should change. I hope this helps.

CodePudding user response:

In JS you can create HTMl Elements by using createElement(tagName). Then you can use innerText or innerHTMl to add text to html to the element. Then you have to append to the parent element.

working example

const ul = document.querySelector('ul');
const ps = ["p1","p2","p3"];
const h4 = document.createElement('h4');

ps.forEach(p => {
  const li = document.createElement('li');
  li.innerHTML = p;
  ul.appendChild(li)
})
<h4>participants:</h4>
<ul></ul>

CodePudding user response:

Why don't you simply add <br> tag at the end of each user record?

showname.innerHTML = '<h4>participants:</h4><br>'   '<ul>'   users.map(function (user) {
    return '<li>'   user   '</li>'   '<br>';
}).join('')   '</ul>';
  • Related