Is this the correct method for linking the function to every individual element?

Is it correct to attach the function to each element individually? Also, is my function correctly implemented?

<ul id='forShopping'>
                    <li><input class='ch' type='checkbox' onclick='isActive()'> Air-freshener</input></li>
                    <li><input class='ch' type='checkbox' onclick='isActive()'> Pampers</input></li>
                    <li><input class='ch' type='checkbox' onclick='isActive()'> Newspaper</input></li>
                    <li><input class='ch' type='checkbox' onclick='isActive()'> Toilet paper</input></li>
</ul>

function isActive () {
    let elem = document.getElementsByTagName('input');
    for(let i=0; i<elem.length; i++){
        if(elem[i].checked == true){
            elem[i].parentNode.style.backgroundColor = 'forestGreen';
        }else{
            elem[i].parentNode.style.backgroundColor = 'white';
        }
    }
}

This approach currently works, but I am uncertain about its correctness.

Answer №1

Even though your code is functional, it can be optimized to reduce costs. Instead of retrieving elements from the DOM on every click and looping through them, consider passing the context of "this" within the function.

This snippet may prove helpful:

JS

function isActive(elem) {
 if (elem.checked == true) {
    elem.parentNode.style.backgroundColor = 'forestGreen';
  } else {
    elem.parentNode.style.backgroundColor = 'white';
  }

}

HTML

<ul id='forShopping'>
  <li>
    <input class='ch' type='checkbox' onclick='isActive(this)'> Air-freshener></li>
  <li>
    <input class='ch' type='checkbox' onclick='isActive(this)'> Pampers></li>
  <li>
    <input class='ch' type='checkbox' onclick='isActive(this)'> Newspaper></li>
  <li>
    <input class='ch' type='checkbox' onclick='isActive(this)'> Toilet paper></li>
</ul>

JSFIDDLE

Answer №2

function toggleColor (element) {
        if(element.checked == true)
         element.parentNode.style.backgroundColor = 'skyBlue';
        else
           element.parentNode.style.backgroundColor = 'white';
}
<ul id='shoppingList'>
                    <li><input class='item' type='checkbox' onclick='toggleColor(this)'> Apples</input></li>
                    <li><input class='item' type='checkbox' onclick='toggleColor(this)'> Bananas</input></li>
                    <li><input class='item' type='checkbox' onclick='toggleColor(this)'> Oranges</input></li>
                    <li><input class='item' type='checkbox' onclick='toggleColor(this)'> Grapes</input></li>
</ul>

Answer №3

Implementing css pseudo-class :checked to style checkboxes without using JavaScript.

Here is an example code snippet:

label {
  display: inline-block;
}
.ch:checked + label {
  background: red;
}
<ul id='forShopping'>
  <li>
    <input class='ch' type='checkbox' />
    <label>Air-freshener</label>
  </li>
  <li>
    <input class='ch' type='checkbox'>
    <label>Pampers</label>
  </li>
  <li>
    <input class='ch' type='checkbox'>
    <label>Newspapper</label>
  </li>
  <li>
    <input class='ch' type='checkbox'>
    <label>Toilet paper</label>
  </li>
</ul>

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

Modifying the style of a specific row when the form is submitted

My webpage contains nested records, with each nested record displaying a total number of clicks in a div labeled "count". I am looking to increment the count by 1 for each specific record when the button with a class of view is clicked. Currently, clicking ...

Navigating through an array of objects with Node.js

Recently, I integrated the ChartJS library into my Node web app to visualize data. The following is nested in a script tag on an EJS template page: <script> let playerStatChart = new Chart(myChart, { type: 'bar', data: { la ...

What is the best way to effectively apply a mask within a PixiJS container so that its color does not display upon page refresh?

After implementing the code snippet below to add a mask in a container, I encountered an issue where upon clicking the refresh button on the page (chrome), the pixi stage would turn completely white until the refreshing process is completed. Can anyone p ...

Are your Promises.all functions executing at the incorrect timing?

I can't seem to understand why Promise.all is not working as expected. Even though the log shows that data for "Streak" and "Last Activity" is successfully retrieved towards the end, I want Promise.all to fetch the data only when everything is filled ...

Can the variable name within a function be retrieved?

How can I retrieve the variable name (user_name1 or user_name2) from a sample function (GetUserName()) within itself? This variable name is required to create an object with the same name on the server side for data synchronization purposes. function GetU ...

move position when clicked-javascript animation

Is there a way to create a button that changes a div's position with a 2-second transition on the first click and then returns it back on the second click? I tried implementing this code, but unfortunately, it doesn't bring the div back. va ...

Tips on expanding the background beyond the boundaries of a parent container with a specific width limit

Could you please take a look at the code snippet below? I am dealing with a situation where I have a container with a fixed width, and inside that container, there are rows whose width exceeds that of the parent container. Some of these rows have a backgro ...

Arrange the list by first names in the array using Ionic 3

What is the process for arranging a list by firstName from an array? This is my code in my.ts file: initializeItems(){ this.items = [ { avatar: '../../assets/imgs/profile1.jpg', firstName:'Sterlian', lastName:'Victorian ...

Implementing global parameters in ui-router

Currently, I am utilizing ui-router in AngularJS as shown below: .state ('browse.category', { url: "/:category", templateUrl: "views/browseCategory.html", controller: function($stateParams, $scope) { $scope.params = $st ...

"Is there a way to retrieve the CSS of all elements on a webpage by providing a URL using

Currently, I am in the process of creating a script that can crawl through all links provided with a site's URL and verify if the font used on each page is helvetica. Below is the code snippet I have put together (partially obtained online). var requ ...

Inline CSS for altering the appearance of text within a DIV container

Within the confines of this DIV element... <div name="layer1" style="background-color:lightblue;"> <hr>Site:Downtown DataCenter Device: 2KBS</hr> </div> Hello there, I am utilizing Inline CSS Styling. Is it possible to make the t ...

Node.js & Express: Bizarre file routes

It's quite strange how my local paths are functioning. Let me show you an example of my directory structure: public > css > bootstrap.css public > js > bootstrap.js templates > layout > page.ejs (default template for any page) tem ...

Vue component not receiving the updated prop value from parent component

I am encountering a problem with my parent-child component setup. The issue arises when I pass a validation field as a prop from the parent to the child, but it doesn't update upon the first click of the submit button in the child component. To explai ...

Test an express + sequelize server using chai-http ping command

Currently facing challenges while setting up tests using Express and Sequelize. The testing framework being used is Mocha + Chai. Initially, only a ping test is being attempted. The code snippet from server.js: const express = require('express&apos ...

Using `await` inside an if block does not change the type of this expression

Within my code, I have an array containing different user names. My goal is to loop through each name, verify if the user exists in the database, and then create the user if necessary. However, my linter keeps flagging a message stating 'await' h ...

Incorporate a dynamic fading effect for text and images using JQuery

I successfully implemented a Crossfade effect using Jquery: function doAnimationLoop(o, n, t, i, a) { fadeInOut(o, n, t, i, function() { setTimeout(function() { doAnimationLoop(o, n, t, i, a) }, a) ...

Is this the proper formatting for JavaScript code?

Having trouble changing the CSS of elements that match b-video > p with an embed element using JQuery. Here's my code: $('div.b-video > p').has('embed').attr('style','display:block;'); Can anyone help me ...

How to automatically choose the first option in a v-for loop in Vue.js

I have a loop that creates a dropdown menu from an array: <select class="form-control" v-model="compare_version" > <option v-for="(version, index) in allVersions" v-bind:value="index" v-bind: ...

Show or hide a div through two variables that toggle between different states

It's possible that I'm not fully awake, so missing the obvious is a possibility. However, I have 2 variables that determine whether a div has a specific class or not. The class functions more like a toggle; so the following conditions should tri ...

Create a timer that plays music when a button is pressed

My goal is to initiate a timer when a specific button is clicked. While there are many timers available that start upon page load, I have not been able to find one that begins upon clicking a button. Additionally, the timer must start at the same time as ...