最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How do I add a class to inner HTML of a div using Javascript? - Stack Overflow

programmeradmin7浏览0评论

I'm trying to work around a seemingly impossible customization for Wordpress. Here is what <?php the_category();?> prints out:

<ul class="post-categories" >
 <li>
  <a rel="category-tag" title="..." href="...">Category One</a>
 </li>
 <li>
  etc.
 </li>
</ul>

I need to add / insert a class into all the <a>'s, to make it look like this:

<ul class="post-categories" >
 <li>
  <a class="btn" rel="category-tag" title="..." href="...">Category One</a>
 </li>
 <li>
  etc.
 </li>
</ul>

So far, I've only found ways to assign additional classes to elements with an existing ID or class. Thanks, in advance, for your help!

I'm trying to work around a seemingly impossible customization for Wordpress. Here is what <?php the_category();?> prints out:

<ul class="post-categories" >
 <li>
  <a rel="category-tag" title="..." href="...">Category One</a>
 </li>
 <li>
  etc.
 </li>
</ul>

I need to add / insert a class into all the <a>'s, to make it look like this:

<ul class="post-categories" >
 <li>
  <a class="btn" rel="category-tag" title="..." href="...">Category One</a>
 </li>
 <li>
  etc.
 </li>
</ul>

So far, I've only found ways to assign additional classes to elements with an existing ID or class. Thanks, in advance, for your help!

Share Improve this question asked Mar 26, 2013 at 20:09 user2213177user2213177 272 silver badges3 bronze badges 2
  • It doesn't seem at all impossible. What have you tried so far? – James Montagne Commented Mar 26, 2013 at 20:12
  • Well - I meant impossible without using js... They make it very difficult to alter certain templates. – user2213177 Commented Mar 26, 2013 at 20:46
Add a ment  | 

3 Answers 3

Reset to default 4

Using jQuery:

$(".post-categories a").addClass("btn");

Since the title says Using JavaScript

Try this for a JavaScript solution:

var links = document.getElementsByTagName("a");

for (var i = 0; i < links.length; i++)
{
    if (links[i].parentNode.className == "post-categories")
    {
        links[i].className = "btn";
    }
}

Or if you're down with the kids and you can use jQuery, you can do:

$(".post-categories > a").addClass("btn");

use jquery

$(function() {
$(".post-categories a").addClass("btn");
})
发布评论

评论列表(0)

  1. 暂无评论