1

I have an array in JS that I get from c# back end as...

<script>        
        var categoryLists = <%= this.javaSerial.Serialize(this.categoryList) %>;
</script>

And my HTML is

<div id="categories">
</div>

What is the best way that I can display the contents of the JS array in the div with id as categories?

PS- I am open to both JS, and Jquery. I also have a huge c# backend.

Beingnin
  • 2,288
  • 1
  • 21
  • 37
  • 2
    @akerr has the best answer - what have you tried thus far? – RockiesMagicNumber Oct 15 '20 at 16:14
  • The "best" way (from the pre-edit) would probably be to generate the HTML in the .aspx file rather than after the page has loaded, so you don't get the FOUC (flash of unstyled content). – freedomn-m Oct 15 '20 at 16:22
  • @freedomn-m... I am putting my html code in the .aspx file and noth .aspx.cs file. –  Oct 15 '20 at 16:47
  • 1
    @RockiesMaginNumber, yes akerr did have the best idea indeed.. I was trying to do a for loop but that didn't turn out to be efficient. I tried a jquery function and that was not working. But no worries coz problem solved :) –  Oct 15 '20 at 16:49

2 Answers2

2

While essentially the same as @akerr's existing js answer, assuming that categoryList outputs as an array, here's a one-liner that will generate the same result.

var categories = ["category 1", "category 2", "category 3"];

$("#categories").append("<ul>" + categories.map((e, i) => "<li>" + e + "</li>").join("") + "</ul>")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="categories">
</div>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
  • This is really clean code. But I am going with the longer version to make it really readable. Thank you :D –  Oct 15 '20 at 16:44
1

Not knowing what the data looks like, I would suggest something like this.

EDIT: Another option that may be a bit cleaner:

JS

let list = document.getElementById('category-list')
categoryLists.forEach(function (category) {
  let li = document.createElement('li');
  list.appendChild(li);
  li.innerHTML += category;
});

JS

let list = document.getElementById('category-list')
for (var category in categoryLists) {
  list.innerHTML += '<li>' + category + '</li>';
  console.log(category);
}

HTML

<div id="categories">
<ul id="category-list">
</ul>
</div>
akerr
  • 355
  • 1
  • 11
  • I'm still sort of new to ES6, and I've read a bit about "let" vs "var" - is there any reason you define the "list" and "li" variables using "let" and then the for loop with a "var"? I'm sure it was just quick typing and also sure it'll work fine either way. Just curious about the semantics. – RockiesMagicNumber Oct 15 '20 at 16:18
  • 1
    let vs var: https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var – freedomn-m Oct 15 '20 at 16:19
  • Thank you, this works perfectly. The data is an array. Sorry, I was not able to reply earlier. :D –  Oct 15 '20 at 16:45