Skip to content
Advertisement

How to recreate the += operator without using it

uh hi guys so im having a problem that i don’t know how to avoid i’m making a dictionary and i know the cause of the problem but don’t really know how to fix it

javascript:

show = function(i) {
    for (let j = 0; j < dictionary[i].content_titles.length; j++) {
        console.log('hi')
        document.getElementById('topic_div').innerHTML +=
`<h3>${dictionary[i].content_titles[j]}</h3>`;
    }
}

html:

<div class="topic" id="topic_div">
  <h3 id="topic_text"></h3>
  <p id="content"></p>
  <hr>
</div>

basically whats happening is since im using the += operator whenever the function activates it runs the for loop all over again, i thought of using a cache but i need the html h3, p, and hr to stay bc that’s going to hold the name and the starting content which is why i can’t delete the html and run it in the for loop with the rest of the titles so how do I fix my problem while keeping the same layout intact

Advertisement

Answer

add another span to contain your content_titles

<div class="topic" id="topic_div">
  <h3 id="topic_text"></h3>
  <p id="content"></p>
  <hr>
  <span id="content_titles"></span>
</div>
show = function(i) {
    document.getElementById('content_titles').innerHTML = "";
    for (let j = 0; j < dictionary[i].content_titles.length; j++) {
        document.getElementById('content_titles').innerHTML +=
        `<h3>${dictionary[i].content_titles[j]}</h3>`;
    }
}

not sure if this is what you wanted, but try it.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement