-1

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.

4
  • 2
    What have you tried and what didn't work as expected? Commented Jul 21, 2022 at 16:52
  • I tried using AppendChild but the username was not showing up. Commented Jul 21, 2022 at 16:58
  • 2
    "I tried using AppendChild" - Not according to the code shown in the question you didn't. Can you update the question to include the relevant code as a runnable minimal reproducible example? "but the username was not showing up" - What username? Not showing up where? Please demonstrate the problem in the question. Commented Jul 21, 2022 at 17:01
  • I edited the question, look again Commented Jul 21, 2022 at 17:19

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

-1

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.

5 Comments

I can't add another element
I'm not sure what you mean. The above code adds what you wanted to a ul element. It doesn't need to be a new element, it can be the one you already have (I assume, you haven't actually shown the code). You're going to need to elaborate more if you want help.
you should not use innerHTML to add tags in HTML. First, you overwrite the current content of that element. Second, it is slow as the DOM needs to be prepared, and third, it opens you up for XSS attacks.
@tacoshy all fair points. What method would you suggest to achieve this?
Either use insertAdjacentHTML or createElement

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.