I’m relatively new to jquery, so I have what I hope will be a simple question.
I need to append multiple spans to the line items in an unordered list.
Essentially, each line item contains a and I need to grab the content of that span and append it to the bottom of the line item it’s 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 + "'s additional info</a></span>");
});
The original HTML it needs to modify:
<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’m getting:
-
John Doe
John is an excellent Swimmer
John DoeJane Doe’s additional info -
Jane Doe
Jane loves to play basketball
John DoeJane Doe’sadditional info
Here’s the desired outcome:
-
John Doe
John is an excellent Swimmer
John Doe’s additional info -
Jane Doe
Jane loves to play basketball
Jane Doe’s additional info
As you can see, instead of taking the all the “Name” var’s and putting them together, instead of just using the “Name” var of that line item.
I’m sure it needs some type of this, $(this), or .each call on it, but I can’t seem to find this in the documentation anywhere.
Can someone help?
Thanks!
Troy
Try this
This will loop through each LI in the UL list and treat them as individual entities. You had two major problems. One is that you were not limiting the context of your jQuery selection so you were getting both “.name” classes and combining them together, that is why you got both names. And then you were adding the values to all LI objects.