"Retrieve the target element using the ID selector when it matches the specified value in

I am struggling to target and display an HTML id tag only when a corresponding JS object in an array has a "live" value of true. How can I achieve this?

My goal is to have a JavaScript loop that displays a link in the schedule module if the link id matches the "scheduleId" of an object, and the "live" value of that object is true. Can you help me with targeting and displaying this link?

Check out my HTML below:



<div class="test-schedule">
   <h2>Schedule</h2>
   <div><span>School of Ed</span><a class="link-class" id="ed">School of Ed link</a></div>
   <div><span>School of Humanities</span><a class="link-class" id="hss">School of Humanities link</a></div>
   <div><span>School of Science</span><a class="link-class" id="sci">School of Science link</a></div>
   <div><span>School of Nursing</span><a class="link-class" id="nursing">School of Nursing link</a></div>
</div>


<style>
.link-class{display:none}
</style>

Here is the JavaScript part:

const eventList = [

  {
    scheduleId: 'ed',
    live: 'true',
  },
  {
    scheduleId: 'hss',
    live: 'false',
  },
  {
    scheduleId: 'sci',
    live: 'false',
  },
  {
    scheduleId: 'nursing',
    live: 'false',
  },
];

Link to Codepen: https://codepen.io/lvl12sealclubber/pen/PoWbJZQ?editors=1011

Answer №1

Are you looking to hide all links and only show some based on a certain JS value? Would this solution work for you:

.link-class {
    display: none;
}
for (let item of itemList) {
    if (item.active) {
        document.getElementById(item.id).style.display = "block";
    }
}

Answer №2

If you're looking to display the link of an event based on whether the event is live or not in the events object, you can achieve this by creating a simple class that will show the element when necessary.

const eventList = [
  {
    scheduleId: "ed",
    live: "true",
  },
  {
    scheduleId: "hss",
    live: "false",
  },
  {
    scheduleId: "sci",
    live: "true",
  },
  {
    scheduleId: "nursing",
    live: "false",
  },
];

const checkLinks = () => {
  for (let event of eventList) {
    if (event.live === "true") {
      document.querySelector("#" + event.scheduleId).classList.add("show-link");
      console.log(event.scheduleId);
    }
  }
};

checkLinks();
.link-class {
  display: none;
}

.show-link {
  display: inline-block;
  color: blue;
}
    <div class="test-schedule">
      <h2>Schedule</h2>
      <div>
        <span>School of Ed </span
        ><a class="link-class" id="ed">School of Ed link</a>
      </div>
      <div>
        <span>School of Humanities </span
        ><a class="link-class" id="hss">School of Humanities link</a>
      </div>
      <div>
        <span>School of Science </span
        ><a class="link-class" id="sci">School of Science link</a>
      </div>
      <div>
        <span>School of Nursing </span
        ><a class="link-class" id="nursing">School of Nursing link</a>
      </div>
    </div>

Answer №3

An improvement could be made by changing the data type of the 'live' property from a string to a boolean.

In a practical scenario, this process would be driven by data, eliminating the need for date comparisons and simply checking if the 'live' property is true or false.

If my understanding is correct, when a user visits this page, the current date/time is calculated to display which event is live. In this case, comparing the current date/time and displaying a link for the live event should suffice. There is no necessity to update the event.live property using JavaScript; in fact, it is advisable not to alter your data in this manner.

Furthermore, rather than dynamically updating the banner style through JavaScript, consider maintaining a placeholder at the top and managing styles via CSS. I fail to see any significant benefit in handling styling with JavaScript.

Answer №4

To display a filtered list of live events, you can use the following method:

const eventList = [{
  scheduleId: 'ed',
  live: 'true',
}, {
  scheduleId: 'hss',
  live: 'false',
}, {
  scheduleId: 'sci',
  live: 'false',
}, {
  scheduleId: 'nursing',
  live: 'true',
}];

const scheduleEl = document.querySelector("#schedule")
eventList
  .filter(event => event.live === 'true')
  .forEach(event => {
    scheduleEl.innerHTML += `<p>- ${event.scheduleId}</p>`;
  });
<p>Live Event Schedule:</p>
<div id="schedule">
</div>

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

Concerns raised about submitting a request through ajax

Having recently delved into the world of ajax and jquery, I have encountered an issue on SO that has left me stumped. Despite searching through multiple threads, I haven't been able to find a solution to the two errors I am facing. OPTIONS http://loc ...

Generate a fresh row in a table with user inputs and save the input values when the "save" button is

HTML: <tbody> <tr id="hiddenRow"> <td> <button id="saveBtn" class="btn btn-success btn-xs">save</button> </td> <td id="firstName"> <input id="first" type="tex ...

Trying to organize JSON data by multiple parameters using jQuery

Regarding the topic discussed in this thread; I have successfully managed to sort an Array of JSON Objects by two fields. Additionally, the discussion mentions: "To include additional columns for sorting, simply add them to the array comparison." // ...

Utilize the latest REDUX state within a React component's function

I'm currently facing an issue in my React application where I am struggling to access the updated state from within a function. Here is a simplified version of my problem: I have a custom React Component to which I pass a variable representing the st ...

Preserve selected option in select box after page refresh in JSP

I'm working on a jsp page that contains a simple select html element. Right now, when I select an option and click the Wyswietl button, the page refreshes, the table data is refreshed, but the selected option resets to default... How can I make it sta ...

Create a new webpage following the slug

Currently in the process of developing a NextJS application, I am utilizing getStaticPaths and getStaticProps to generate static pages and handle necessary requests for them. The goal is to create all pages following the URL structure: challenge/[slug]/ w ...

Steps for launching Angular 5 application using Node.js server

I have developed an Angular 5 application that retrieves data from a node.js server. I successfully deployed the application to my web server hosted by FastComet, which supports node.js, but unfortunately, the server does not seem to be functioning properl ...

How can one transfer information from a client to a server and complete a form using JavaScript?

Can the information be transferred from a client to the server using just JS, then fill out a form on the server, and finally redirect the client to view a pre-filled form? I am considering utilizing AJAX to send a JSON object, but unsure if it will be s ...

Why is the text returned by the Angular Response body missing the JSON brackets? Strange, isn't it

As a newcomer to Angular 2, I should mention that some information is internal and will be replaced with placeholders when needed. My current task involves making a simple post request and retrieving the contents of the request body. Below is my existing ...

Each time I attempt to update my profile on the web application, I receive this notification

Working on creating a web app using react, redux, and node for managing profile data. I have a function that controls both creation and editing of profiles. The creation works fine, but I encounter an error message when trying to edit. I've reviewed m ...

What is the best way to utilize Link for navigation in React with Material UI?

const pages = ['home', 'menu', 'reservation']; <Box sx={{ flexGrow: 1, display: { xs: 'none', md: 'flex' } }}> {pages.map((page) => ( <Link component={Link} to='/'>Home</L ...

Unpacking JSON data and mapping JPA entities

I have two entities named X and Y that are related in a @ManyToMany relationship. X contains a list of Y's, referred to as yList. Both X and Y have other attributes that are not relevant to this scenario. For my JPA provider, I am utilizing Hibernate ...

creating a number + i formatted array in R

I am interested in creating an array in R where each number is incremented by a specific value according to the following parameters: i<-2 array1<-c(1:100) The desired array should look like this: 1,3,5,7,9, ...100 Thank you very much. ...

What is the best way to iterate through an array of dynamic form inputs and distribute them into multiple tables?

I'm working on a master form for entering recipes into a database. While most of the form is functioning correctly, I am facing an issue with inserting multiple ingredients into the database. I believe I need to use an array to store the inputs for i ...

In three.js, it is important to understand that Vertex and Vector3 are not simply

When I started using three.js revision 48, I created vertices connected by lines without any issues. However, upon updating to revision 65 from 48, an error message appeared stating that Vertix is deprecated and should be replaced by Vector3. Unfortunately ...

Display a multiline bash variable in order to send a JSON payload with curl

I am currently working on a script that utilizes the Github API to post a comment with the output of a specific command. The command's output consists of multiple lines. My current approach involves: curl -H "Authorization: token oauthtoken" \ ...

What is the correct way to format JSON files for writing?

I encountered an issue while trying to store user favorites in a JSON file. The error message I received is: Unhandled Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>&ap ...

Unable to switch checkbox state is not working in Material UI React

I am experiencing an issue with the Material UI checkbox component. Although I am able to toggle the state onCheck in the console, the check mark does not actually toggle in the UI. What could be causing this discrepancy? class CheckboxInteractivity exten ...

Add HTML to a div element using jQuery when content is replicated through JavaScript

I have encountered an issue while appending HTML from a dynamically created div using JavaScript. The problem arises when I try to append the HTML multiple times - each time it adds the content twice, thrice, and so on. This is possibly happening because i ...

When attempting to retrieve JSON data from MySQL in Python, an error is encountered stating: "TypeError: the JSON object must be a string

Why am I encountering an error when trying to retrieve JSON from MYSQL? And how can I resolve this issue? `def get_go(order_no): mycursor.execute("SELECT `order_details` FROM `orders` WHERE `order_no` = " + str(order_no)) myresult = mycursor.fe ...