0

I have jQuery read some text then add a class based on the value of this text. (The text read is rendered by my CMS).

The HTML Looks like this:

<ul class="zoneSubscriptions">
 <li>
   <ul>
      <li class="zoneName"><a href="#">Professional</a></li>
      <li>Never</li>
   </ul>
 </li>
 <li>
   <ul>
     <li class="zoneName"><a href="#">RTTM</a></li>
     <li>Never</li>
   </ul>
 </li>
</ul>

I want to read the text of class="zoneName"and add a class based on this.

JS to do this:

$(function() {
   var zone = $( ".zoneName" ).text();
   $( "#zones" ).addClass( zone );
});

This works without issue, however, I need it to add two classes, Professional and RTTM. What it adds is ProfessionalRTTM.

My question is how would I add the classes while keeping a space between the words?

In other words it should render like this: class="Professional RTTM" not class="ProfessionalRTTM"

Note: In my example there are two "zoneName"s. There could be anywhere from 1 to 5 or more when used live.

4 Answers 4

3

Try iterating the tags:

var $zones = $("#zones");

$(".zoneName").each(function () {
  $zones.addClass( $(this).text() );
});

Also possible (if you want to reuse the list of class names)

var classes = [];
$(".zoneName").each(function () {
  classes.push($(this).text());
});

$("#zones").addClass(classes.join(" "));
Sign up to request clarification or add additional context in comments.

Comments

2

You're calling .text() on multiple results which is joining them together.

Why not do something like this instead:

var zone = $( ".zoneName" ).each(function(){
    $("#zones").addClass($(this).text());
});

Find all your .zoneNames and then call addClass for each one.

jsFiddle example

Comments

1

You need to iterate across the .zoneNames, otherwise your .text() will be a one undivided string (unless you have whitespace in there)

$(".zoneName").each(function() { 
    $("#zones").addClass($(this).text());
});

Comments

0

You can use the callback function of addClass(), and use map() to get an array of the text, then simply join with a space:

$('#zones').addClass(function() {
    return $('.zoneName').map(function() {
        return $(this).text();
    }).get().join(' ');
});

Here's a fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.