user3590212
user3590212

Reputation: 47

How to display.textcontent with objects

How do I iterate through an object that will be displayed on the webpage by using display.textContent.

Given that

var list = {x:1, y:2, z:3};
for (var property in list){
   div.textContent = (list[property])
} 
//Displays 3.  
//Div is referring to my HTML page.

I want to be able to display 1, but then after a button is clicked, it will than display 2, 3, etc.. How could I do that?

Upvotes: 0

Views: 1950

Answers (3)

CodingIntrigue
CodingIntrigue

Reputation: 78585

You could try something like this:

    var list = {x:1, y:2, z:3},
        index = 1, // Store the current iteration
        keys = Object.keys(list); // Grab all the keys for the object
    var button = document.querySelector("button"),
        div = document.querySelector("div");
    // Bind your click handler
    button.addEventListener("click", function() {
        // Might want to do something after '3'
        if(index >= keys.length) return;
        // Otherwise set the content from the key at 'index' and increment
        // the index for the next click
        div.textContent = list[keys[index++]];
    });
<div>1</div>
<button>Next</button>

Upvotes: 1

How to display 1,2,3 every time a button is clicked?

function displayResult(){
  var list = {x:1, y:2, z:3};
  var div = document.querySelector("#myDiv"); //getting my div element

  var text = new Array();

  for (var property in list){
    text.push(list[property]) //adding values in text array
  }

  div.textContent = text.join(",") //array concatenation
}
<div id="myDiv"></div>

<button onclick="displayResult()">Display</button>

Upvotes: 0

Sergey Maksimenko
Sergey Maksimenko

Reputation: 588

You don't store previous value of div.textContent, so you see only last iteration result. Try this

   var list = {x:1, y:2, z:3};
   div.textContent = "";
   for (var property in list){
       div.textContent = div.textContent + " " + (list[property]);
   } 

Upvotes: 1

Related Questions