'Hide section when there's no messages to display

I need to hide the div when there are no messages to display, Javascript is used to display the messages. I have tried solutions to similar questions with no success.

HTML:

 <div class="msgList">
    <section id="messages">
        <h2>Messages</h2>
        <ul id="users-messages">

        </ul>
    </section>
</div>

JavaScript:

// Display messages in list
const messageSection = document.getElementById('messages');
const messageList = messageSection.children[1];
const newMessage = document.createElement('li');
newMessage.classList.add('msg-List');
newMessage.innerHTML = `<a href="mailto:${user_email.value}">${user_name.value}</a>. 
<span id="msg-span"> wrote: ${user_message.value}</span>`;


Solution 1:[1]

You can use conditional for user_message.value. You add the style of display none to your message section if user_message.value is null or empty.

Otherway is you can set the innerHTML as an empty string if there is no message.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hasna Hena Mow