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>