Reputation: 45
I have an online menu that is being generated from a CRM. Each item can be classified by the client within the CRM with one of 3 values. So I have worked out how to get the values and write them into the proper place. What has tripped me up is the level of specificity that is needed to loop through each item, find the class names and then apply them to each item without effecting the other menu items.
I can use a CRM tag that will write the item id into each class so I can have the ability to parse each one and use the parent class to only effect the spans that are with that item... i.
<div class="menu-item-123"> <!-- Each Class modified by CRM id -->
<!-- Item in the span below are dynamically generated -->
<span class="items" style="display:none;">Signature,NewItem</span>
<!-- jQuery writes list above into classes below -->
<p class="item-type">
<span class="icon gf"></span>
<span class="icon new"></span>
<span class="icon sig"></span>
</p>
</div>
Now I just need help with how to make jQuery do it's ".each()" function the why I envision it should. I'm feeling like there needs to be one function to parse the list of class names from the generated list and then another function to get the parent class and write it to only those span items. My jQuery skills are intermediate at best so I apologize for my lack of knowledge on this matter...
$("div[class*='menu-item-'] .items").each(function() {
var result = $(this).html();
//replace commas to create class names
var list = result.replace(/,/gi, " ");
//add class names to span.icon
$("span.icon").addClass(list);
});
You can see on the fiddle below that the ".each()" is effecting all the items the same why even though the list of classes on each is varied. This is where my jQuery skill limit has landed me. Thanks in advance for any help!
Fiddle link here - http://jsfiddle.net/archetypestudio/77rvc/1/
Upvotes: 1
Views: 872
Reputation: 388316
It is because of your selector
$("div[class*='menu-item-'] .items").each(function() {
var result = $(this).html();
//replace commas to create class names
var list = result.replace(/,/gi, " ");
//add class names to span.icon
$(this).next().children("span.icon").addClass(list);
});
Demo: Fiddle
Your selector $("span.icon")
targets all span.icon
in the dom, instead what you need is the span.icon
which is in the next p
of the current .items
element.
Upvotes: 1