Ratnesh
Ratnesh

Reputation: 1700

Print set element in javascript

I am trying to print the set element through innerHTML, but I am not getting the desired result. While I tried with document.write(),it is printing but I want to use only innerHTML.

Here is my source code:

  <div id="demo"> </div>  
  <script type="text/javascript">
     var i, item;
     var setObj1 = new Set();
     for(i=0;i<5;i++)
     setObj1.add(i);

     for (item of setObj1.values())
     //document.write(item+",");
     document.getElementById('demo').innerHTML="The set value is: "+ item;         
  </script>

Output: 4

Desire output: 0 1 2 3 4

Please suggest me how to use innerHTML to print the output.I have tried console log and document.write(), they are working.

Upvotes: 20

Views: 34543

Answers (7)

random-forest-cat
random-forest-cat

Reputation: 35894

if you want to avoid traditional looping you could also use Array#from

const iterator = new Set([ 1, 1, 2, 3 ])

console.log(
  Array.from(iterator) // prints unique Array [1, 2, 3]
)

Also works better for non-browser targets like node where the output of Set is shortened

Upvotes: 24

Nimantha Fernando
Nimantha Fernando

Reputation: 403

Only showing 4 happens due to overwriting the innerHTML of the demo div in each of the iteration.For avoiding this happen, it is needed to concatenate the values within the for loop and set innerHTML after all iteration completes.

   let endVal = "";
   for (item of setObj1.values()) {
       endVal += item + " ";
   }

   document.getElementById('demo').innerHTML = "The set value is: "+ endVal;

Upvotes: 0

quirimmo
quirimmo

Reputation: 9988

With your code, you will see only the last element.

The reason is that for each element in your Set, you are changing the content of your div inserting the new string. So at the end only the last one will be shown.

If you want to keep all of them, you can concatenate the content of your div at each iteration:

const setObj1 = new Set();
for (let i = 0; i < 5; i++)
  setObj1.add(i);

for (let item of setObj1.values())
  document.getElementById('demo').innerHTML += "The set value is: " + item + "<br/>";
<div id="demo"></div>

You can also evaluate to use appendChild if you want to append new HTML elements inside your div, rather than just changing the HTML content of your div

Upvotes: 2

Nick Parsons
Nick Parsons

Reputation: 50684

You have a few issues:

  1. You need to add (append) to the end of your innerHTML, at the moment you are overwriting the content at each iteration of your loop. Instead, you should use += to add to the content in the div.

  2. You're querying the DOM (document object model) an unnecessary amount of times. You really only need to query it once. Using document.getElementById is an expensive operation to run, thus it is ideal to run it a minimum amount of times.

  3. Use .textContent instead of .innerHTML. If you are not appending or adding HTML, you don't need to use .innerHTML, .textContent will do the trick. It is a good habit to get into using .textContent when only dealing with text. This can help you avoid issues such as XSS vulnerabilities (in future programs if you have user input)

See working example below (read code comments for further explanation):

const setObj1 = new Set();
for (let i = 0; i < 5; i++)
  setObj1.add(i);

const outputElement = document.getElementById('demo'); // get the element you wish to add to
let toAppend = "The set value is: "; // create a string of the content you wish to add
for (let item of setObj1.values())
  toAppend += item + ' '; // build up the content you wish to add by adding to the string
  
outputElement.textContent += toAppend; // only once the loop is done add your content to the page (the DOM)
<div id="demo"></div>

Upvotes: 2

Josep Alsina
Josep Alsina

Reputation: 3027

From es5, the most concise way is the spread (...) operator, that works with any Iterable collection:

console.log([...mySet].join(' '));

Upvotes: 8

jlents
jlents

Reputation: 820

You can also achieve it by converting to an array using the spread operator and then joining, if you're looking for a one liner:

// Establishing a set 
let mySet = new Set(['a', 'b', 'c']);

// Printing the set, space delimited 
console.log(new Array(...mySet).join(' '));

Upvotes: 22

Mamun
Mamun

Reputation: 68933

You can store all the value in a variable and then set that to the the element. Please note you can use textContent or innerText when the htmlString is only text.

<div id="demo"> </div>  
<script type="text/javascript">
   var i, item;
   var setObj1 = new Set();
   for(i=0;i<5;i++)
   setObj1.add(i);
   var val = ''
   for (item of setObj1.values())
    val+=item + ' '; 

   document.getElementById('demo').textContent = "The set values are: "+val;
</script>

Upvotes: 3

Related Questions