What is the best way to assign various classes to individual elements depending on their content?

HTML

<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-401 dt-mega-menu mega-auto-width mega-column-3">
    <a href='#' data-level='1'>
        <i class="logo-png dnld-logo"></i>
        <span class="menu-item-text">
                <span class="menu-text">Download App</span>
        </span>
    </a>
</li>
<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-71">
    <a href='#' data-level='1'>
        <i class="logo-png subs-logo"></i>
        <span class="menu-item-text">
                <span class="menu-text">Purchase Subscription</span>
        </span>
    </a>
</li>
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-74 has-children">
    <a href='#' class='not-clickable-item' data-level='1'>
        <i class="logo-png help-logo"></i>
        <span class="menu-item-text">
                <span class="menu-text">Help</span>
        </span>
    </a>
    <ul class="sub-nav gradient-hover hover-style-click-bg level-arrows-on">
        <li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-66 first">
            <a href='#' data-level='2'>
                <i class="logo-png faqs-logo"></i>
                <span class="menu-item-text">
                        <span class="menu-text">FAQS</span>
                </span>
            </a>
        </li>
        <li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-68">
            <a href='#' data-level='2'>
                <i class="logo-png vid-logo"></i>
                <span class="menu-item-text">
                        <span class="menu-text">Instructional Videos</span>
                </span>
            </a>
        </li>
    </ul>
</li>

There are over 20 elements structured like the above examples. Each innermost span should have a different class applied only when clicked, defining the color of the text.

JQuery

(function($) {
    $(document).ready(function() {
        $('li.act > a > i').removeClass('logo-png').addClass('activatedd');

        function addEventListenerByClass(className, event, fn) {
            var list = document.getElementsByClassName(className);
            for (var i = 0, len = list.length; i < len; i++) {
                list[i].addEventListener(event, fn, true);
            }
        }

        addEventListenerByClass('menu-item', 'click', showIcon);

        var cssClasses = ['home-text', 'about-text', 'print-text', 'dnld-text', 'subs-text', 'help-text', 'sorks-text', 'cont-text', 'work-text', 'col-text', 'body-text', 'hst-text', 'space-text', 'cell-text', 'organ-text', 'system-text', 'cs-text', 'ae-text', 'ag-text', 'bsi-text', 'med-text', 'tudors-text', 'roma-text', 'vict-text', 'vik-text', 'ww-text', 'ss-text', 'pe-text', 'sc-text', 'faqs-text', 'vid-text', 'email-text', 'trial-text', 'next-text'];


        function showIcon() {
            $("#primary-menu .act").removeClass("act");
            $("#primary-menu .activatedd").removeClass("activatedd").addClass("logo-png");
            //Add active class for its parent if it is level 1
            $(this).addClass("act").parents("li").addClass("act");
            $('> a > i', $(this)).removeClass("logo-png").addClass("activatedd").parents().find("li.act>a>i.logo-png").removeClass("logo-png").addClass("activatedd");
        }
    })
})(jQuery);

var cssClasses contains all the classes that we have to apply. In the provided HTML example,

<span class="menu-text">Download App</span>
will be assigned the dnld-text class. However, when another element is clicked (e.g., FAQs), the previous class needs to be removed and replaced with the class related to this new element along with its parent's class. The JavaScript function written performs a similar action for icons, but it applies and removes the same class from all elements. We can target specific elements based on their class, such as $('i + span > span'). How should I modify this functionality?

Answer №1

It seems that in order to address your concern, there is no necessity to include those classes; simply utilize CSS along with a structure that targets the i element when it possesses the class .activatedd, like this example for the Download Text:

The current CSS styling you have for .dnld-text should be transformed into:

i.dnld-logo.activatedd + .menu-item-text .menu-text {
  color: red;
}

Here’s a breakdown of the steps:

  • Select the menu-text element
  • This element should be a child of menu-item-text
  • And also be a sibling of the i element with the class dnld-logo when it is marked as activatedd

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

"UIWebView experiences a crash when a long press gesture is performed on a textarea element

Looking to implement a custom keyboard for UIWebView that is entirely based on HTML/JS/CSS for compatibility across multiple devices. To achieve this, I included a notification as shown below: [[NSNotificationCenter defaultCenter] addObserver:self selecto ...

Content displayed in the center of a modal

Struggling to center the captcha when clicking the submit button. Check out the provided jsfiddle for more details. https://jsfiddle.net/rzant4kb/ <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class=" ...

Enhance your picture links with a:hover box-shadow styling

I've been struggling to add a box shadow on hover to a Facebook icon image. I assumed it would be straightforward, but as always, I was wrong. I'm working with a child theme in WordPress because I recently started, thinking it would be an easy wa ...

execute a rigorous compilation during the ng build angular process

I am currently working on a project using angular-cli and I have configured my package.json with the following scripts: "scripts": { "ng": "ng", "build": "ng build --base-href /test/", "prod": "ng build --prod --base-href /test/" } According to the ...

Navigating through tables and selecting rows

I am currently facing an issue with my HTML table that consists of 1000 rows and 26 columns. To navigate between rows and make selections, I have implemented a jQuery plugin on the table. The problem lies in the performance of the plugin, even with the la ...

Iterate through JSON data and delete based on date values

I have a JSON file that stores user information. As time progresses, some comments may become outdated and I am searching for a solution to remove comments that are older than 3 days and update the JSON file. Here is an example of the JSON data: [{"EngCom ...

The function $.get does not function correctly when added to Button.ClientSideEvents.Click during the second click

string okumagecmisiStr = string.Format("function(s,e){{ $.get('/GetHazirRapor.ashx?RaporTanimi={0}',function(data){{location.href='{1}'}} ); }}", hrt.ID, hrt.WebRaporLink); ButtonWebRaporAc.ClientSideEvents.Click = okumagecmisiStr; T ...

How to retrieve the value of a SelectField component within a constant using Material-UI

I am currently facing an issue with my Drawer component that contains a SelectField with some fields. I am struggling to get the value and implement the onChange functionality of the Field. Below is the snippet of my code: const DrawerCargoAddItem = (p ...

Create a random number on the server every X interval

Context I have developed a Node.js application that generates a random number every 6 seconds and exposes it through an API. To maintain separation of concerns, I decided to encapsulate the number generation logic in a function called numberGen, stored i ...

Execute a function with parameters when a button is clicked dynamically using PHP

I am trying to execute a parameterised function in PHP using AJAX. Below is the code snippet of my dynamic button where I need to pass $sub_id to the delet(sub_id) function for executing some SQL: echo "<td><input type='submit' name=&a ...

Tips for creating a dynamic system to continuously add more HTML tables in PHP

I am working with an HTML table where the data is retrieved from a database. I need to add new rows to enter additional data, but the numbering does not continue from the last number. My question is how can I increase the numbering in the table. Please ref ...

looping through a linked data object with ng-repeat

I am working with a Node object in my Angular controller. Each Node contains a next property which points to the next item: $scope.Stack = function () { this.top = null; this.rear = null; this.size = 0; this.max_size = 15; ...

"Did you come across `item()` as one of the methods within the array

While studying the book 'JavaScript and jQuery Interactive Front-End Web Development', I came across this interesting sentence: You can create an array using a different technique called an array constructor. This involves using the new keyword ...

What is the best way to use ajax to send a specific input value to a database from a pool of multiple input values

Welcome everyone! I'm diving into the world of creating a simple inventory ordering site, but am facing a roadblock with a particular issue: Imagine you have a certain number (n) of items in your inventory. Based on this number, I want to run a &apos ...

Should PHP be avoided in CSS files?

I've recently developed a CSS page named style.php and at the beginning, I included this line: <?php header("Content-type: text/css"); ?> What are your thoughts on this approach? Is it considered a bad idea? The reason behind doing this is tha ...

Modify the collapse orientation in Bootstrap

I would like the button to expand from the bottom when clicked and collapse back down, instead of behaving like a dropdown. <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_ ...

Problem arises with chai-http middleware when employing dynamic imports in chai 5.1.1 version

Currently, I am utilizing npm chai version 5.1.1 which has transitioned to supporting only imports and not requires. My use of dynamic imports has been successful so far. However, I have encountered an issue when incorporating the chai-http middleware with ...

Using data binding in VueJS to construct a dynamic URL

Exploring VueJS for the first time and it's been a great experience so far. However, I'm facing a couple of challenges with data binding. The requirement is for the customer to input an image URL, and no image should be displayed until a valid ...

"Utilize an HTML input to query and retrieve data stored in a

Seeking to retrieve data from my MySQL database and display it on the website securely. List of existing files: /includes db_connect.php functions.php getdata.php logout.php process_login.php psl-config.php register.inc.php /j ...

How do I switch back and forth between displaying content as 'none' and 'block' using JQUERY?

Take a look at this code snippet. <div class="sweet-overlay" tabindex="-1" style="opacity: 1;display: none;"></div> Is there a way to switch the style attribute value from none to block and back? ...