Modify a JavaScript class using d3 select and filter operations

I have a function that I've been working on.

Initially, I change all classes to "badge badge-secondary". Then, I check the text in the span. If it says "right" and is clicked, I update it to "badge badge-primary". If the text is "wrong" and clicked, then I change it to "class", "badge badge-danger".

I'm wondering if there's a way to make my code more concise and efficient?

function updateOrderType(ansType) {
    lastAnsType = ansType;
    var ansBadge = d3.select("#anstype").selectAll("span.badge");
    ansBadge.attr("class", "badge badge-secondary");
    ansBadge.filter(function() {
        if (d3.select(this).text() == ansType) {
            return d3.select(this).text() == "right";
        }
    }).attr("class", "badge badge-primary");
    ansBadge.filter(function() { 
        if (d3.select(this).text() == ansType) {
            return d3.select(this).text() == "wrong";
        }
    }).attr("class", "badge badge-danger");
}

Answer №1

The code you provided may be a bit challenging to comprehend at first glance, but based on the initial logic presented, I would suggest the following approach:

function updateOrderType(ansType) {
    var ansBadge = d3.select("#anstype").selectAll("span.badge");

    ansBadge.forEach(function() {
        var oElement = d3.select(this);

        if (/**CLICKED**/) {
            var sText = oElement.text();

            if(sText === "right") {
                oElement.setAttribute("class", "badge badge-primary");
            } else if(sText === "wrong") {
                oElement.setAttribute("class", "badge badge-danger");
            } else {
                oElement.setAttribute("class", "badge badge-secondary");
            }

        } else {
            oElement.setAttribute("class", "badge badge-secondary");
        }
    }
}

Your previous version of the code looped through the ansBadge array almost 5 times, evaluating 1 if statement each time. The revised suggestion above only iterates once and contains a maximum of 3 if conditions. You could further optimize by checking for cases where the element is not clicked in the outer if, as this scenario is more common.

This code handles four types of elements:

  • clicked & "right" > primary
  • clicked & "wrong" > danger
  • clicked with any text > secondary
  • not clicked with any text > secondary

Answer №2

A summary of georgina95's response

function updateOrderType(ansType) {
    var ansBadge = d3.select("#anstype").selectAll("span.badge");

    ansBadge.forEach(function() {
        var oElement = d3.select(this);
        var newClass = "badge badge-secondary";

        if (/**CLICKED**/) {
            var sText = oElement.text();

            if(sText === "correct") {
                newClass = "badge badge-primary";
            } else if(sText === "incorrect") {
                newClass = "badge badge-danger";
            }
        }
        oElement.setAttribute("class", newClass);
    }
}

Answer №3

Thank you for all your assistance. Initially, I encountered an issue where I couldn't use the forEach method with d3.select (v4). It's an object that doesn't support attr but instead uses setAttribute. As a result, I had to modify my code:

function updateOrderType(ansType) {
    d3.select("#ordertype").selectAll("span").each(function() {
        var badgeText = this.textContent;
        if(ansType === badgeText) {
                if(ansType === "right") {
                    this.setAttribute("class", "badge badge-primary");
                } else if (ansType === "wrong") {
                    this.setAttribute("class", "badge badge-danger");
                } else {
                    this.setAttribute("class", "badge badge-secondary");
                }
        } else {
            this.setAttribute("class", "badge badge-secondary");
        }
    });
}

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

The parameter is causing the Aggregate Function to malfunction

When fetching MongoDB data, I encountered an issue. Using the JavaScript parameter to retrieve data from MongoDB resulted in a null return, but manually typing it brought all the data without any problems. That part is working fine. const data = await Numb ...

Positioning the comments box on Facebook platform allows users to

Need assistance, I recently integrated the Facebook comments box into my Arabic website, but I am facing an issue where the position of the box keeps moving to the left. Here is an example of my website: Could someone please suggest a solution to fix the ...

Node.js express version 4.13.3 is experiencing an issue where the serveStatic method is not properly serving mp3 or

I am currently utilizing Express 4.13.3 along with the serve-static npm module to serve static assets successfully, except for files with mp3 or ogg extensions. Despite reviewing the documentation, I have not come across any information indicating that thi ...

Is there a way to prevent Chrome from highlighting text that matches the content of a `position: fixed` element?

I currently have a Toc element in my HTML with the property position: fixed. (This means it remains in place as you scroll) My goal is to prevent Chrome's Find Text feature from recognizing text within that Toc element. (Ideally using JavaScript) ...

typescript unconventional syntax for object types

As I was going through the TypeScript handbook, I stumbled upon this example: interface Shape { color: string; } interface Square extends Shape { sideLength: number; } var square = <Square>{}; square.color = "blue"; square.sideLength = 10; ...

Selecting meteor.js user logout functionality

Is there a reliable method for detecting when a user logs out of the website? I have some maintenance tasks that need to be handled upon logout. The website is built using meteor.js user accounts. I will also be implementing validation features, so it&apo ...

Tips for concealing the values within a selected dropdown list using jQuery

Hello, I'm currently working on a jQuery application that involves a dropdown list box and a gridview. The first column of the gridview has checkboxes with a check all button at the top. My goal is to disable corresponding values in the dropdown list ...

The Design and Layout of a MEAN Stack Application

When creating a MEAN Stack app using the express-generator npm, everything worked perfectly but I found myself confused about the purpose of certain files. For instance: The package.json included this code snippet: "script":{"start": "node ./bin/www"} ...

Issue with React tabulator ref being null after re-rendering

Utilizing Tabulator within React by employing the react-tabulator module has been a part of my development process. Now, I rely on 'ref' for the table component to execute actions such as downloading data or any other relevant activity. import R ...

convert a screenplay to javascript

I have a script that can be used to calculate the distance between 2 coordinates. The code is a combination of PHP and JavaScript. I am interested in moving it into a standalone JavaScript file but not sure how to proceed. Below is the script related to & ...

I must address the drag-and-drop problem in reverse scenarios

I am currently utilizing react-dnd for drag and drop feature in my color-coding system. The implementation works flawlessly when I move a color forward, but encounters an issue when moving backward. Specifically, the problem arises when shifting a color ...

What could be causing this Angular controller to throw the error message "Error: Unknown provider: nProvider <- n"?

Check out the jsFiddle code here: <div ng-app=""> <div ng-controller="FirstCtrl"> <input type="text" ng-model="data.message" /> {{data.message + " world"}} </div> </div> function FirstCtrl($scope) { ...

Exploring the functionality of the limitTo syntax within ng-repeat operation

Recently, I started using AngularJS version 1.4.x. {{ limitTo_expression | limitTo : limit : begin}} In my ng-repeat loop, I want to apply a limitTo:10:{head.value}* 10 filter. But I am not sure how to make it work correctly. I am trying to incorporate ...

Why doesn't Mongoose automatically generate an _id for my array elements when I push them in?

I am looking for a way to have mongoose automatically add an _id field to the objects I push into my array. Here is my mongoose schema: var playerModel = new Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "Users", }, cl ...

Using Selenium to interact with a link's href attribute through JavaScript

New to Java and Selenium, I'm facing difficulties when trying to click on a link with JavaScript in href attribute. Here's the snippet from the page source: href="javascript:navigateToDiffTab('https://site_url/medications','Are y ...

List being dynamically split into two unordered lists

Could someone help me with a JS/jQuery issue I'm facing? My challenge is to populate a modal when a link is clicked. Upon clicking the link, a UL is created from a data attribute. However, the problem is that only one UL is being generated whereas I ...

Invoking servlet using Ajax

I have created a JSP file with Javascript functions and AJAX calls to invoke a servlet (ReadprojectInfo). <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE ...

Encounter an issue while attempting to generate a multidimensional array in JQuery

I am trying to utilize jQuery to create a multi-dimensional array. Below is the code snippet I have written for reference: GiftData = []; GiftData['boxProduct'] = []; GiftData['boxName'] = jQuery('#giftbox-data .box-data').te ...

What is the best approach for assigning initial values to data retrieved from Vuex?

My objective is to develop an 'edit account' form where users can update their account details. I aim to display the account information in a pre-filled form that includes fields like username, email, and address. Users will be able to make chan ...

CSS Style in Safari does not conceal Div on Tailwind

When switching the screen from desktop to mobile in ReactJS/Tailwind, I have hidden certain images using the following code: <div className="flex shrink flex-row justify-between w-[60%] h-[25%] sm:w-[95%] sm:h-[52%] mb-[-10px] mt-[-15px] lg:mt-0&qu ...