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.
Advertisement
Answer
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>