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

128
Visualizações
How to change background of heading which is in loop of twig using Javascript

I am new to JavaScript. I want to display names that are in an array and each name with data are put in heading tag . I want to change the background color of the heading with each click on the heading. I am using a twig to loop contents.

What I have tried is :

<div class="inbox_chat">
          {% set newArray = [] %}
          {% for msg in msg_details %}
          {% if msg.to_name not in newArray %}


        <div class="chat_list active_chat">
          <div class="chat_people">
            <div class="chat_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> </div>
            <div class="chat_ib">
             <h5 id="txt-msg" onclick="viewMessage('txt-msg')">{{msg.to_name}} <span class="chat_date">{{msg.time}}</span></h5>
              
            </div>
          </div>
        </div>
        {% set newArray = newArray|merge([msg.to_name]) %}
         {% endif %}
        {% endfor %}
          </div>

Javascript Code

<script>

function viewMessage(elementId){
document.getElementById(elementId).style.backgroundColor = 'green';
 }
 </script>

Here the only first name of displaying names changes when clicks. If I click another name in the list, then also the first name color changes. If I click a name on the list, I want to change that clicked name background color only. Not the first one background color.

What my output shows:

Output

How to change the background color of the name when clicks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When you add the same id to multiple HTML elements and later on try to select an individual element by that id, javascript will select the first id that it could find in DOM, so that's why each id should be unique.

to solve this you can remove id and add the same class to elements, then pass this to the function that you are calling. when the function is called it will select all elements in the dom (with querySelectorAll) that has that class and remove styles from them, then will select the elements that you passed with this, and will change the color.

  <body>
    <h5 class="name" onclick="viewMessage(this)">this is a name</h5>
    <h5 class="name" onclick="viewMessage(this)">this is a name</h5>
    <h5 class="name" onclick="viewMessage(this)">this is a name</h5>
    <h5 class="name" onclick="viewMessage(this)">this is a name</h5>

    <script>
      function viewMessage(element) {
        document.querySelectorAll('.name').forEach((e) => (e.style = ''))
        element.style.backgroundColor = 'green'
      }
    </script>
  </body>

or you can use addEventListener to achieve the same thing with out onclick attribute on your elemnts. here is the code:

  <body>
    <h5 class="name">this is a name</h5>
    <h5 class="name">this is a name</h5>
    <h5 class="name">this is a name</h5>
    <h5 class="name">this is a name</h5>

    <script>
      const allNames = document.querySelectorAll('.name')

      allNames.forEach((names) => {
        names.addEventListener('click', (element) => {
          removeColor()

          element.target.style.backgroundColor = 'green'
        })
      })

      function removeColor() {
        allNames.forEach((name) => (name.style = ''))
      }
    </script>
  </body>
about 4 years ago · Juan Pablo Isaza 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