JQuery - Get multiple spacing text with one class?

I am relatively new to jquery, so I have what I hope will be a simple question. I need to add some spacing to the positions in an unordered list.
Essentially, each position contains an a, and I need to grab the contents of that range and add it to the bottom of the position it is contained in. Here's what I have so far:

My jquery code:

  $("ul").ready(function(){
    var Name = $(".name") .text();
    var Content = $(".content") .text();
    $("li") .append("<span class=\"additional\"><a href=\"/addinfo.php\">"+ Name +" additional info</a></span>"); 
 });

      

Original HTML to be changed:

<ul>
  <li>
  <span class="name">John Doe</span><br />
  <span class="content">John is an excellent Swimmer</span><br />
  </li>
  <li>
  <span class="name">Jane Doe</span><br />
  <span class="content">Jane loves to play basketball</span><br />
  </li>
</ul>

      

Here's the output I get:

  • John Doe
    John is a great swimmer
    John DoeJane Doe more info

  • Jane Doe
    Jane loves to play basketball
    Doe Jan Dawson More Info

Here's the desired output:

  • John Doe
    John is a great swimmer
    John Doe More info

  • Jane Doe
    Jane loves to play basketball
    Jane Doe More info

As you can see, instead of taking all the "name" var and adding them together, instead of just using the "Name" var at that position. I'm sure it needs some type for this: $ (this) or .each, but I can't find it in the documentation.

Can anyone please help? Thank you! Troy

+1


a source to share


2 answers


try it

$("ul > li").each(function() {
    var Name = $(".name", this) .text();
    var Content = $(".content", this) .text();
    $(this).append("<span class=\"additional\"><a href=\"/addinfo.php\">"+ Name +" additional info</a></span>");
});

      



This will go through each LI on the UL listing and treat them as separate entities. You had two major problems. First, you are not restricting the context of your jQuery selection, so you get both ".name" classes and concatenate them together, so you get both names. And then you added values ​​to all LI objects.

+7


a source


It's right here: http://docs.jquery.com/Core/each#callback

I would assign a class to all LI elements and then



$(".li-class").each(function(){
    var Name = $(".name", this) .text();
    var Content = $(".content", this) .text();
    $(this) .append("<span class=\"additional\"><a href=\"/addinfo.php\">"+ Name +" additional info</a></span>");
});

      

0


a source







All Articles