Modify the background color of paragraph using JavaScript based on the outcome

I am trying to update the background color of a search result in a paragraph tag based on a condition where the value of a variable is greater than 1. I believe this can be achieved using an if statement. Below is the code snippet I am currently working on:

const todos = [{
  text: 'Order airline tickets',
  completed: false
},{
  text: 'Vaccine appointment',
  completed: true
}, {
  text: 'Order Visa',
  completed: true
}, {
  text: 'Book hotel',
  completed: false
}, {
  text: 'Book taxi to airport',
  completed: true
}]

const filters = {
  searchText: ''
}

const renderTodos = function (todos, filters) {

    // Filter the todos based on the search text and assign it to filteredTodos variable
    const filteredTodos = todos.filter(function (todo) {
        return todo.text.toLowerCase().includes(filters.searchText.toLowerCase())
    })

    const notDone = filteredTodos.filter(function (todo) {
      return !todo.completed
    })
    
    // Clear the div containing the results before displaying new results
    document.querySelector('#todos').innerHTML = ''

    const summary = document.createElement('h4')
    summary.textContent = `You found ${notDone.length} incomplete tasks in this search`
    document.querySelector('#todos').appendChild(summary)

    // Loop through each todo object, create a p tag for the title searched and append it to the div
    filteredTodos.forEach(function (todo) {
        const noteEl = document.createElement('p')
        noteEl.textContent = todo.text
        document.querySelector('#todos').appendChild(noteEl)
    })

    elem = document.createElement("hr")
    document.querySelector('#todos').appendChild(elem)
}

document.querySelector('#search-todo').addEventListener('input', function (e) {
  filters.searchText = e.target.value
  renderTodos(todos, filters)
})

If there are incomplete todos in the paragraphs being appended to my #todos div, I would like to apply a yellow background color to those specific p tags.

Thank you!

Answer №1

To ensure proper highlighting, include the following if condition within the forEach loop:

if (!task.completed) {
    display.style.backgroundColor = "yellow";
}

Your complete loop should be structured as follows:

filteredTasks.forEach(function (task) {
    const display = document.createElement('p');
    display.textContent = task.text;
    if (!task.completed) {
        display.style.backgroundColor = "yellow";
    }
    document.querySelector('#tasksList').appendChild(display);
})

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

What is causing the colored SVG to appear lighter than the intended color after using a mask to recolor it?

I have a project using VueJS where I am trying to change the color of SVGs by looping through them and using mask and rect tags. However, I am noticing that as the icon index increases, the color of the icon becomes lighter. What could be causing this issu ...

Preventing browser freeze by using window.addEventListener in React

I'm new to React and I'm facing an issue where the code seems to freeze the browser (I'm using Chrome) when I click multiple times on the window. Can someone help me understand why? import "./App.css"; import { useState } from &quo ...

Why doesn't the background color display properly when the div height is set to auto?

When I set the height of #container to auto, the background-color does not display. However, when I set it to a fixed height like 1000px, it shows up. I've attempted using "overflow:auto", but that did not solve the issue. How can I fix this? I want # ...

Tips for incorporating external routes into the routes index file

I am currently dealing with a users.js and an index.js file. users.js const express = require('express'); const router = express.Router(); const {catchErrors} = require('../handlers/errorHandlers'); const authController = require(&ap ...

Is using setTimeout in a group of promises blocking in JavaScript?

Is it possible for multiple requests to be queued up and executed in sequence when calling the function func? The third promise within func includes a lengthy setTimeout that can run for as long as 3 days. Will additional calls to func trigger one after an ...

Utilizing BeautifulSoup to Extract Links

Currently, I am extracting cricket schedules from a specific website using Python's Beatiful Soup library. The webpage I am scraping corresponds to the following URL: www.ecb.c0.uk/stats/fixtures-results?m=1&y=2016 This particular link displays ...

css, align top menu

Is it possible to achieve this using only CSS? Please take a look at my example here. Currently, when I hover over the menu, the submenu appears next to it. I would like to align all submenus' tops with the top of the second level menu. ---------- ...

Does the value of an Angular reactive form control only reflect what the user inputs?

I am working with a reactive form where I need to extract values and assign them to a variable defined in an interface. The form is populated using the Google Places API, which disables user interaction with all controls except for the initial address inpu ...

Received the error message "Material-UI: capitalize(string) expects a string argument" while implementing the snackbar feature in a React Material-UI project

While working with Material-UI, I came across an issue with the snackbar where I received an error message saying: Error: Material-UI: capitalize(string) expects a string argument. Here's a snippet of my code: this.state = { snackBarOpenVer ...

Ways to retrieve a variable within the init() function

My current project involves using datatables along with ajax to display information dynamically. Below is the code snippet I am working with: // Setting up the module var DatatableAdvanced = function() { // Examples of Basic Datatables var _c ...

Top method for tracking changes in numerous textboxes

I'm currently working on a form that is organized into tabs using jQuery. Each tab contains different elements of the form related to a specific section, with a save button at the bottom of each tab. I want to implement a feature where a warning icon ...

Utilizing jQuery to implement a CSS style with a fading effect, such as FadeIn()

I have a jQuery script that applies a CSS style to an HTML table row when the user clicks on a row link: $(this).closest('tr').css("background-color", "silver"); Is there a way to soften this color change effect, such as by gradually fading in ...

Multi selection dropdown feature in Angular failing to populate the options

I am working on a small Angular controller that manages a dropdown menu, with the second dropdown menu populating based on the selection made in the first one. Despite my best efforts, I can't seem to populate the dropdown menus with any content from ...

Maintain the grouping of elements within a div when printing in Internet Explorer 8

When printing in IE8, I'm facing an issue with keeping the "Table title" line on the same page as the <table>. Despite using page-break-inside:avoid;, there is still a page break between the table title and the actual table. My expectation is f ...

Ways to conceal a div in React when the input or child is not in focus

My custom search and select component includes an input field and a results list enclosed in a wrapper container: <div className='wrapper'> <input /> <div className='results'> <div>Result Item</div> ...

Tips on displaying just two buttons in one line

When using *ngFor to display multiple buttons, all buttons appear in one column. I want to have only 2 buttons in a row: the green buttons in one line, and the red buttons in the next line. How can I achieve this? Here is what I have tried: <div class= ...

Guide on updating a table row upon clicking the edit button in an Angular 12 template-driven form

Currently, I have set up a table where the data can be edited by clicking on a hyperlink and then saving the changes with a button. The issue I am facing is that when I click on the edit link, all rows become editable instead of just the specific row I cli ...

Having difficulty accessing information from Firebase database using the .once() function

When a button is clicked on the page, I need to fetch data from a Firebase database using the once() function. Despite setting up the necessary references and variables, the data retrieval seems to be unsuccessful as the global variable numElections keeps ...

Unable to retrieve response token from form in a Next.js/React application utilizing Cloudflare Turnstile

As a beginner in Next.js/React, I'm currently working on creating a basic contact form with Cloudflare Turnstile integration. Prior to implementing Turnstile, the form functioned perfectly, submitting data to the API and sending emails without any iss ...

Steps to handle the change event of a p:inputText element

In my current setup, I am utilizing p:inputText and have the need to trigger a javascript function that will update the searchField in the backend bean. <p:inputText required="true" placeholder="#{cc.attrs.searchTip}" value="#{cc.attrs.queryProperty}" ...