skip to Main Content

I am working with a chatbot interface and I need to retrieve the message id and add it to the submit function. I attempted to use $(".msf-text").id, but it returned undefined. How can I retrieve the id? It is important to note that there are multiple messages within the msg-text class, and I would like the submit function to contain the id of the submitted message.

randomeIndex = getRandomInt(100000000)
message_index = randomeIndex
<div class="msg-text" id="message-${message_index}">${text}</div>  

    msgerForm.addEventListener("submit", event => {
   
    
      const message_id = $(".msf-text").id
      console.log("message id is " + message_id)
}

2

Answers


  1. Use jQuery::prop() method to access a DOM property of the first element in a jQuery object:

    https://api.jquery.com/prop/

    (you made a type also .msf-text => .msg-text)

    const message_id = $(".msg-text").prop('id');
    

    Or (make sure the element exists):

    const message_id = $(".msg-text")[0].id;
    
    Login or Signup to reply.
  2. You may consider not using jQuery. Here’s a minimal reproducable example
    to retrieve the last element of a collection of specific elements.

    // assign id to all .msg-text for demo
    document.querySelectorAll(`.msg-text`)
      .forEach((msg, i) => msg.id = `message-${i + 1}`);
    
    // retrieve the last message id:
    console.log([...document.querySelectorAll(`.msg-text`)].pop().id);
    
    // when the elements are embbeded in a root element
    // (for demo this is the case)
    // you can use the :last-child pseudo selector
    console.log(document.querySelector(`.msg-text:last-child`).id);
    <div>
      <div class="msg-text">message 1</div>
      <div class="msg-text">message 2</div>
      <div class="msg-text">message 3</div>
      <div class="msg-text">message 4</div>
      <div class="msg-text">message 5</div>
      <div class="msg-text">message 8</div>
      <div class="msg-text">message 7</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search