Generating a bullet list from an array of objects

Looking to create an unordered list with vanilla JS, using an array of objects to populate the list. Struggling a bit on how to accomplish this.

Here is my current code:

let myObj = [
  {name: "Harry Potter", author: "JK Rowling"},
  {name: "Hunger Games", author: "Suzanne Collins"},
  {name: "Lord of the Rings", author: "J. R. R. Tolkien"},
  {name: "Game of Thrones", author: "George R.R. Martin"},
  {name: "Percy Jackson", author: "Rick Riordan"},
];

console.log(myObj);

let myUL = document.createElement("UL");
myUL.setAttribute("id", "myUL");
document.getElementById("myDiv").appendChild(myUL);
for (const item of myObj) {
   document
   .getElementById("myUL")
   .appendChild(document.createElement("LI"));
}
<div id="myDiv"></div>

Struggling to format my list to look like this:

  • JK Rowling: Harry Potter
  • Suzanne Collins: Hunger Games
  • J. R. R. Tolkien: Lord of the Rings
  • George R.R. Martin: Game of Thrones
  • Rick Riordan: Percy Jackson

Any tips on accomplishing this using vanilla JS would be appreciated!

Answer №1

To create a <strong> tag containing item.author, it's recommended to utilize the createElement method.

You can then generate a new text node for item.name by using document.createTextNode.

Finally, attach the textNode to the li element and append it to the ul:

const myObj = [
  {name: "Harry Potter", author: "JK Rowling"},
  {name: "Hunger Games", author: "Suzanne Collins"},
  {name: "Lord of the Rings", author: "J. R. R. Tolkien"},
  {name: "Game of Thrones", author: "George R.R. Martin"},
  {name: "Percy Jackson", author: "Rick Riordan"},
];

const myUL = document.createElement("UL");
myUL.setAttribute("id", "myUL");

const ul = document.getElementById("myDiv").appendChild(myUL);

for (const item of myObj) {
    let author = document.createElement("strong");
    author. textContent = item.author + ': ';
    
    let li = document.createElement("li");    
    li.appendChild(author);
    li.appendChild(document.createTextNode(item.name))
    
    ul.appendChild(li);
}
<div id="myDiv"></div>

Answer №2

If you need to customize your unordered list, make the necessary changes in the JavaScript code below:

let myList = [
  { title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
  { title: "To Kill a Mockingbird", author: "Harper Lee" },
  { title: "1984", author: "George Orwell" },
  { title: "Brave New World", author: "Aldous Huxley" },
];

let ulElement = document.createElement("ul");
ulElement.setAttribute("id", "myList");

for (const item of myList) {
  let liItem = document.createElement("li");
  liItem.textContent = `${item.author}: ${item.title}`;
  ulElement.appendChild(liItem);
}

document.getElementById("listContainer").appendChild(ulElement);

In this updated script, individual list items are created and added to the unordered list element. To display titles in bold format, you can utilize <strong> or <b>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing Text in React Native is Customizable

As a newcomer to react native, I find myself in need of some guidance. I am currently working on implementing a TextInput feature where users can update the text value as they please. For instance, if a user initially creates a folder named "Bar" but later ...

Tips for updating an Observable array in Angular 4 using RxJS

Within the service class, I have defined a property like this: articles: Observable<Article[]>; This property is populated by calling the getArticles() function which uses the conventional http.get().map() approach. Now, my query is about manually ...

Highcharts 3D Pie Chart with Drilldown Feature

How can I create a 3D Pie Chart with Drilldown effect? I am having trouble understanding how it works. Here is a JsFiddle Demo for a 3D Pie Chart: JsFiddle Demo And here is a JsFiddle Demo for a 2D Pie Chart with Drilldown feature: JsFiddle Demo You can ...

Add a click event listener to the body element using a button click, without causing it to trigger

What is the current situation: A button is clicked by the user The menu opens (list items display = block) The function to close the menu is connected to the <body> The function to close the menu is immediately triggered, causing the menu to close ...

showing the data in a textbox using AJAX retrieved information

I have a table where additional rows can be added by the user with the click of a JavaScript function. Each row contains a drop down list, and based on the selected value, an AJAX script fetches some values to display in corresponding textfields within th ...

Retrieve the AngularJS scope object by using an alternate scope object as the identifier

As I loop through an array of person objects using ng-repeat, imagine the array looks something like this: [{ "display_name": "John Smith", "status": "part-time", "bio": "I am a person. I do people stuff.", }, { "display_name": "Jane Doe", "stat ...

Store data in Firebase Storage and retrieve the link to include it in Realtime Database

Utilizing Firebase Realtime Database and Firebase Storage for this application involves uploading images from the pictures array to Firebase Storage. The goal is to obtain the Firebase Storage link for each image, add it to the object pushed into imagesU ...

Exploring the intricacies of Knockout JS mapping nested models using fromJS function

I am struggling with understanding how to effectively utilize the Knockout JS Mapping Plugin. My scenario involves nested models, and currently I am only using the ko.mapping.fromJS() in the parent model. However, I have noticed that the computed values ar ...

The div structure generated through JavaScript appears distinct from its representation in the live DOM

Currently, I am facing a challenge with creating a complex nested Div structure within a JavaScript loop that iterates over JSON response objects from the Instagram API. The main goal is to set the URL for each image within a specific Bootstrap div layout. ...

Guide to generating a PDF file and utilizing a Node.js program for the download process

Seeking assistance in creating a button using my Node.js application to generate a downloadable PDF file filled with information from a PostgreSQL database. Any help is greatly appreciated! ...

Utilizing the jQuery slideToggle method on the specified target element

I'm encountering an issue with jQuery slideToggle, and here's the code I have: $(".dropdownmainmenu").click(function(){ $(this).children(".showmenu").slideToggle(); $(this).toggleClass("activemainmenu"); $(this).find(".showarrowmainmen ...

Error: The function is not defined on this.props during the handleCHange event

After going through numerous answers to similar questions on this topic, I believe that I am following all the necessary steps but for some reason, it is not working. Below is the specific section of code that is causing the error: import React from &apos ...

Streamlining the process of implementing click events on elements selected by class using jQuery

Slowly but surely, I am gaining familiarity with jQuery and have reached the point where I desire to abstract my code. However, I am encountering issues when attempting to define click events during page load. Within the provided code snippet, my objectiv ...

Obtain the date in ISO format without subtracting the timezone offset

I need to obtain a Date string without the timezone being added or subtracted. Currently, when I set my OS timezone to GMT +13 and create a new Date() object, the toISOString() method subtracts one day. For example, today is 11/02. If I adjust my OS time ...

When Using TypeScript with Serverless, 'this' Becomes Undefined When Private Methods are Called from Public Methods

Currently, I am working on constructing an AWS Serverless function using TypeScript. My focus is on creating an abstract class with a single public method that invokes some private methods. Below is the simplified version of my TypeScript class: export ...

Guide to creating dynamic borders around your PHPexcel output

Looking for assistance on adding borders around output arrays in an Excel report using PHPexcel. I reviewed the documentation, but the examples are static, requiring a predefined number to set. My goal is to have all arrays transferred to Excel with bord ...

Enhance your JavaScript skills by deserializing objects and seamlessly integrating new methods

Currently in my Javascript code, I am utilizing localStorage. Since objects cannot be directly stored in it, I am using JSON.stringify to serialize them before saving. Within localStorage, I am storing the entire game state, where some of the sub-objects ...

Encountering an issue when attempting to downgrade React Native version from 0.51 to 0.45

My current project requires me to downgrade due to certain third-party packages not being updated for the latest version of react-native. Specifically, I am using Xcode 9.0. Despite my efforts to downgrade the react-native version, I encountered the follo ...

The unusual behavior of the :to attribute on @click in Vue

I have a specific element: Hashtag.vue: <template> <router-link :to="getTo" custom v-slot="{ navigate }"> <div role="link" @click="navigate"> {{text}}</div> </rout ...

What is the proper method for submitting a mail form via AJAX without using jQuery?

Currently, I am working on integrating a PHP mail form with AJAX. The aim is to create a straightforward form that collects user information such as phone numbers and sends it to my email address. While I have managed to set up the form to send emails usi ...