'which/how to properly use a loop for html change with Javascript?

I am new in Javascript and trying to change the HTML content of a line.

I've been helped a little by a friend who made this code for me, but I'm running into major issues.

The situation is: I'm creating a FAQ in SharePoint 2013, and this code is supposed to read a list, read 3 informations (Category, Question and Answer) and then substitute the HTML where I want it to.

The issue is that it is running on every '.cd-faq__trigger' that is inside it's "i.category", changing them all to the same "i.question"

function ChangeHTML(){
        var items = GetListItems("X", "Y", "Z")

        items.forEach(function(i){ 
            $('#'+i.category+' .cd-faq__trigger').html(i.question)
        });
        }
    }
-----------------HTML ------------------

<div class="cd-faq__items">
    <ul id="Compras_TI" class="cd-faq__group">
        <li class="cd-faq__title"><h2>Compras TI</h2></li>
        <li class="cd-faq__item">
            <a id="trigger" class="cd-faq__trigger" href="#0"><span id="texto"></span></a>
        </li>
    </ul>
</div>
    


Solution 1:[1]

Finally figured out how to do it... Made the script write the whole HTML from scratch and then no need to substitute nothing.

SCRIPT:

 function AddCategory(){
        var items = GetListItems("ListID", "caml", "url")
        items.forEach(function(i){ 
            $('#'+i.Categoria).append('<li class="cd-faq__item"><a id="trigger" class="cd-faq__trigger trigger" href="#0"><span>'+i.Pergunta+'</span></a><div class="cd-faq__content"><div class="text-component"><p>'+i.Resposta+'</p></div></div></li>')  
        });
    } 

'i.Categoria' = each category from the list.
'i.Pergunta' = each question posted on the list.
'i.Resposta' = each answer posted on the list.

HTML:

<div class="cd-faq__items">
      <ul id="Compras_TI" class="cd-faq__group">
             <li class="cd-faq__title"><h2>Compras TI</h2></li>       
      </ul> <!-- cd-faq__group -->
</div>
        

So it looks for the Category of the post, and inside of it it appends the HTML adding in it the question and answer posted.

Thank you for who helped!

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 Luiz Ribas