Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

160
Visualizações
how to add element to html with javascript

How can I put this code inside <ul> with javascript?

<li>
  <span class="username">nickname:</span> message
</li>

Edit: I'm making a chat website and I want to bold the username part, but I can't.

website image

Code:

var socket = io();

var messages = document.getElementById('messages');
var form = document.getElementById('form');
var message = document.getElementById('messageinput');
var username = document.getElementById('usernameinput');

form.addEventListener('submit', function(e) {
  e.preventDefault();
  if (!username.value) {
    var item = document.createElement('li');
    item.textContent = `Error: Write a username`;
    item.style.background = '#ff5e69'
    messages.appendChild(item);
    window.scrollTo(0, document.body.scrollHeight);
  } else {
    if (message.value) {
      socket.emit('chat message', {
        username: username.value,
        msg: message.value
      });
      message.value = '';
    }
  }
});

socket.on('chat message', function(data) {
  var item = document.createElement('li');
  item.textContent = `${data.username}: ${data.msg}`;
  messages.appendChild(item);
  window.scrollTo(0, document.body.scrollHeight);



});
<ul id="messages">


</ul>
<form id="form" action="">
  <input id="messageinput" autocomplete="off" /><button>Send</button>
  <input id="usernameinput" autocomplete="off" />
</form>

I am using this code, I tried many things to make the username bold but none of them worked.

about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

you can do it like this:

var element = document.getElementById("one");
var newElement = '<div id="two">two</div>'
element.insertAdjacentHTML( 'afterend', newElement )
// new DOM structure: <div id="one">one</div><div id="two">two</div>

I leave a reference link

Link:https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

about 4 years ago · Santiago Gelvez Relatório

0

Try

 document.querySelector("#your_fav_form").addEventListener("submit", (e) => {
    e.preventDefault()

    let username = document.querySelector("#username").value.trim();

    if (username == ""){
      let message = document.querySelector("#message");
      let li = document.createElement("li");
      li.setAttribute("class", "username");
      li.innerText = "Please enter your username";

      if (message.innerText.trim() == "") {
        message.appendChild(li);
      }
    } else {
      alert("your socket logic goes here");
    }
  });
.username{
      font-weight: bold;
<ul id="message"></ul>

<form id="your_fav_form" method="POST" action="">
  <input
    type="text"
    id="username"
    name="username"
    autocomplete="off"
    data-id="username"
  />
  <button type="submit">Submit Form</button>
</form>

about 4 years ago · Santiago Gelvez Relatório

0

EDIT: As pointed out in the comments by tacoshy there are a few potential issues with this method. These issues are:

  • Content already found in the element will be overwritten
  • This method is slower as the DOM needs to be prepared
  • This method could potentially open up the possibility of XSS attacks if the inner html is set from user input.

Due to these potential issues, it may be better to go with one of the other options on this question.


If your ul has an id you could do something like this:

var htmlToAppend = '<li><span class="username">nickname:</span> message</li>'
var element = document.getElementById("list")

element.innerHTML = htmlToAppend
<ul id='list'>

</ul>

Where the innerHTML attribute of element is the HTML contained by the element. Editing this attribute will immediately reflect on the page.

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda