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.

4
  • 2
    @akerr has the best answer - what have you tried thus far? Commented Oct 15, 2020 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). Commented Oct 15, 2020 at 16:22
  • @freedomn-m... I am putting my html code in the .aspx file and noth .aspx.cs file. Commented Oct 15, 2020 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 :) Commented Oct 15, 2020 at 16:49

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

This is really clean code. But I am going with the longer version to make it really readable. Thank you :D
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>

3 Comments

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.
Thank you, this works perfectly. The data is an array. Sorry, I was not able to reply earlier. :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.