I have a situation where I am sorting through a list of blog posts in a custom CMS. Each blog post is wrapped in a <li> and there are multiple posts on the page. I have code that puts in a sharethis button set on each blog post. Unfortunately all the class names for a blog post start with “post”. For example;
<div class="blogList">
<ul>
<li class="post1">
<h2 class="postTitle">A Sample Title</h2>
<div class="postDescription">Some sample content</div>
</li>
<li class="post2">
<h2 class="postTitle">A Sample Title</h2>
<div class="postDescription">Some sample content</div>
</li>
</ul>
</div>
I was sorting through this with an “.each” on the li but that ended up adding it to the lists that are included in any post content itself. So I want to only add this once onto the actual parent li of each individual blog post.
What I’m trying to do is add it only to the <li> with a class of “post” and then a number. I can’t just look for post since it also will add it onto any other item with the class of “post” as it’s starting name.
How can I select only the elements with only the class of “post” and a number? So I would want to find only elements in the above example of li.post1, li.post2 . All other elements would be skipped.
I’m doing this in jquery and I feel like I’m close but just can’t seem to get over this hump.
Below is the code example I’m using in it’s entirety.
<script type="text/javascript">
$(document).ready(function(){
//Run through the page and find each individual blog post
$('.blogList li [class^="post"]').each(function () {
//Grab post title & encode any quotes so they don't mess up generated HTML
var postTitle = $.trim($(this).children(".postTitle").text().replace('"g, "'));
//Grab URL from the anchor element inside the h2 element (will not grab correct link in admin mode)
var postLink = location.protocol + '//' + location.host + $(this).children("h2").find("a[href]").attr('href');
//Add "share this" HTML elements to the bottom of the post
$(this).append(
'<div class="st">' +
'<span class="st_twitter" displayText="Tweet" st_url="' + postLink + '" st_title="' + postTitle + '"></span>' +
'<span class="st_facebook" displayText="Facebook" st_url="' + postLink + '" st_title="' + postTitle + '"></span>' +
'<span class="st_linkedin" displayText="LinkedIn" st_url="' + postLink + '" st_title="' + postTitle + '"></span>' +
'<span class="st_email" displayText="Email" st_url="' + postLink + '" st_title="' + postTitle + '"></span>' +
'<span class="st_blogger" displayText="Blogger" st_url="' + postLink + '" st_title="' + postTitle + '"></span>' +
'<span class="st_sharethis" displayText="ShareThis" st_url="' + postLink + '" st_title="' + postTitle + '"></span>' +
'</div>'
);
});
});
</script>
You just need to use a more specific class selector. This rule should get what you need:
That will get you only direct child li’s with a class of post* that are direct children of a UL that is a direct child of a div with a class of blogList.