What is the best way to utilize jquery for selecting elements from an array and applying a class to them?

My goal is to apply the "hide" class to the child element based on the data-node-tag attribute of the parent element from an array. I have managed to log the array successfully, but I am struggling to use the values from that array in order to add the class.

For context, the array is extracted from a cookie called collapsed_Nodes, which has been split into individual elements.

In my implementation, I am utilizing js.cookie and jQuery. You can view my code on JS Fiddle.

$(document).ready(function() {
  var adjustCookie = function() {
    var tags = [];
    $('.accordion_container .hide').each(function() {
      var tag = $(this).prev('.accordion_head').data("node-tag");
      tags.push(tag.replace('#', '#'));
    });

    if (tags.length) {
      Cookies.set('collapsed_Nodes', tags.join('|'), {
        expires: 7
      });
    } else {
      Cookies.remove('collapsed_Nodes');
    }
  }
  
  $(".accordion_head").click(function() {
    var tag = $(this).data("node-tag");
    if ($(this).next(".accordion_body").is(':visible')) {
      $(this).next(".accordion_body").slideUp(300);
      $(this).next(".accordion_body").addClass("hide");
      $(this).children(".plusminus").text('+');
    } else {
      $(this).next(".accordion_body").slideDown(300);
      $(this).next(".accordion_body").removeClass("hide");
      $(this).children(".plusminus").text('-');
    }
    adjustCookie();
  });
  
if (document.cookie.indexOf('collapsed_Nodes') >= 0) {
var getCollapsed = Cookies.get('collapsed_Nodes');
  var Collapsed = getCollapsed.split('|');
  var arrayLength = Collapsed.length;
  for (var i = 0; i < arrayLength; i++) {
      $("data-node-tag".Collapsed[i]).next(".accordion_body").addClass("hide");
  }
}
});
.accordion_container {
  width: 500px;
}

.accordion_head {
  background-color: skyblue;
  color: white;
  cursor: pointer;
  font-family: arial;
  font-size: 14px;
  margin: 0 0 1px 0;
  padding: 7px 11px;
  font-weight: bold;
}

.accordion_body {
  background: lightgray;
}

.accordion_body p {
  padding: 18px 5px;
  margin: 0px;
}

.plusminus {
  float: right;
}

.hide {
  display: none;
}
<div class="accordion_container">
  <div class="accordion_head" data-node-tag="#1">First Accordian Head<span class="plusminus">-</span>
  </div>
  <div class="accordion_body">
    <p>First Accordian Body, it will have description</p>
  </div>
  <div class="accordion_head" data-node-tag="#2">Second Accordian Head<span class="plusminus">-</span>
  </div>
  <div class="accordion_body">
    <p>Second Accordian Body, it will have description</p>
  </div>
  <div class="accordion_head" data-node-tag="#3">Third Accordian Head<span class="plusminus">-</span>
  </div>
  <div class="accordion_body">
    <p>Third Accordian Body, it will have description</p>
  </div>
</div>

Answer №1

One alternative method is to target the div using its attribute value:

$('[data-node-tag="'+checkCollapsed[i]+'"]').next(".accordion_body").addClass("hide");

Check out the code on JSFiddle: https://jsfiddle.net/yuvakqha/22/

Answer №2

Your current selector is incorrect; the class should precede the attribute, and the attribute should be enclosed in brackets []

Try using this corrected version:

$("." + Collapsed[i] + "[data-node-tag]").next(..).addClass("hide")

https://api.jquery.com/has-attribute-selector/

This function selects elements that contain the specified attribute, regardless of its value.

Here's a simplified example to illustrate:

$(".accordion_head[data-node-tag]").addClass("red");
.red {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="accordion_container">
  <div class="accordion_head" data-node-tag="#1">First Accordian Head<span class="plusminus">-</span>
  </div>
  <div class="accordion_body">
    <p>First Accordian Body, it will have description</p>
  </div>
  <div class="accordion_head" data-node-tag="#2">Second Accordian Head<span class="plusminus">-</span>
  </div>
  <div class="accordion_body">
    <p>Second Accordian Body, it will have description</p>
  </div>
  <div class="accordion_head" data-node-tag="#3">Third Accordian Head<span class="plusminus">-</span>
  </div>
  <div class="accordion_body">
    <p>Third Accordian Body, it will have description</p>
  </div>
</div>

Answer №3

Make a modification here:

$("data-node-tag".Collapsed[i]).next(".accordion_body").addClass("hide");

Change it to:

$(Collapsed[i]).next(".accordion_body").addClass("hide");


Upon applying the split() method, the Collapsed variable will produce an array.

Array [ "#2", "#3" ]

Following your for loop, the output will be:

#2
#3

Hence, you can use a jQuery selector to target them like any other ID

$( Collapsed[i] )

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

Global variable appears undefined in Angular 2 view, yet it is still displaying

I'm running into issues with my Angular 2 code. Inside my ts file, I have the following: import { Test } from '../../../../models/test'; import { TestService } from '../../../../services/test.service'; import { Job} fr ...

The execution of the function halts as soon as the player emerges victorious

In my attempt to create a basic game where players compete to click their designated button faster to reach 100%, I am in need of assistance with implementing a logic that determines the winner once one player reaches or exceeds 100. Essentially, I want ...

css Apply styles to form controls only if they are not empty

Utilizing an angularjs form, I have customized the following example to fit my code: .my-5 { margin:100px; } .form-group { position: relative; margin-bottom: 1.5rem; } .form-control-placeholder { position: a ...

The hover effects in CSS3 create unexpected interactions with surrounding elements in Chrome

Recently, I added a CSS3 hover effect to one of the images on my website following this tutorial: http://tympanus.net/Tutorials/OriginalHoverEffects/index2.html However, after implementing the hover effect in Chrome, I noticed that some other elements on ...

Using React to Grab Initial List with AJAX Request

Recently, I began delving into React and came across a compelling example in the official documentation on how to initially load data via AJAX: var LatestUserGists = React.createClass({ getInitialState: function() { return { userna ...

Utilizing jQuery to implement the functionality of closing a lightbox div when clicking on a

Is there a way to include a function in my confirm function that will close a specific lightbox div .productInformation? Snippet of jQuery Code: $('body').on("click", "#product_delete_product", function (e) { e.preventDefault(); var box ...

Experiment with a ThreeJS, Websockets, and NodeJS Client/Server Interaction

Exploring the possibilities of socket.io, ThreeJS, Javascript, and NodeJS, I embarked on a project to create a simple client/server setup using ThreeJS's graphics. While uncertain if these frameworks would seamlessly integrate, I decided to take a cha ...

Unforeseen Extra Information is being transmitted along with Socket.io and Jquery

Issue : There seems to be a problem with the chat message printing an extra character in msg. Upon console logging, an additional object value is appearing in the state. What could be causing this issue? Console log output : 2{"message":"e"} 1{"mess ...

Using a semicolon in the fall through of a switch case statement

When working with a fall-through in a case statement, is there any significance to including a semicolon? It seems that the fall-through functions as expected, and the semicolon may just be interpreted as an empty statement. But are there any advantages or ...

Is there a way to determine the number of syllables in text as it is being typed?

Working on a React-based web app, I am trying to determine the number of syllables in a textarea as the user types. Encountering errors like "cannot find length of a null" at every turn. Right now, all I want is to utilize console.log() for troubleshooti ...

What is the method for specifying a string argument type from a string list and executing a mongo db query?

Is there a way to specify the argument type in a function as a string from a list of strings in order to run a MongoDB query? Here is what I am currently attempting: users.services.ts async findOne(key: "_id" | "email" | "username", value: string) { ...

Is there a detailed HTML page specifically designed for CSS testing?

I am in search of sample code featuring the use of semantic HTML to test stylesheets. The version/doctype is flexible, but HTML5 would be preferable. By "comprehensive," I mean incorporating definition lists, forms, tables, and all other standard element ...

Unable to locate three.js library

Hey there, I'm currently working on creating the "get started" application from the three.js website. For reference, you can check out their guide at . Here's a snippet of the HTML code I've put together: <!DOCTYPE html> <html lan ...

The fixed header column doesn't remain sticky

I am working on fixing the first column in my table to remain static on mobile devices so that users can easily identify the data they are viewing when scrolling. While the td elements in the table work perfectly as intended, the column header continues to ...

What can I do to prevent my CTA image with a width of 100% from distorting when I change the height?

Creating a website and in need of a CTA image? Utilizing Bootstrap 4 along with custom CSS to tweak the appearance, I've set it to occupy the entire width of the screen using width: 100%;. As the screen size changes, the image remains responsive, adju ...

NextJS: Invalid element type provided: expected a string for built-in components or a class/function for composite components, but received an undefined value

Utilizing Nextjs, I've configured an index.js file in the /pages directory and a meta.js file in the /components/meta/ directory. However, during the rebuild process of my application, I encountered the following error message: Element type is inv ...

Using data across multiple instances in node.js EJS partials

I need some advice regarding my nodejs project. I have created a sidebar partial that requires user data to be displayed on it. This sidebar is utilized across multiple pages in the project. However, currently, I have to include the user data in every func ...

When Buttons Decide to Take a Break: A Guide to What Happens After You Click Them

Looking for some assistance with my code! I have a set of two buttons and when the user clicks on either one, it triggers a function (which is working perfectly). However, if the user clicks again on the same button, I want it to do nothing. Here is my HT ...

Building a bespoke pagination feature with react-table

Looking to personalize the pagination with links for "Previous," page numbers, and "Next" like this example: https://i.sstatic.net/C4vsw.png I'm currently using react-table version 7 but have been unable to replicate the desired pagination style. I ...

Download functionality is functional in Chrome but not in Explorer when using jQuery

I have implemented the following code to facilitate file downloads directly to the desktop: $('#resourceTable tbody').on( 'click', '#getFile', function () { var data = resourceTable.row( $(this).parents('tr& ...