user2213177
user2213177

Reputation: 27

How do I add a class to inner HTML of a div using Javascript?

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!

Upvotes: 2

Views: 6111

Answers (3)

Mathew Thompson
Mathew Thompson

Reputation: 56429

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");

Upvotes: 3

Tamil Selvan C
Tamil Selvan C

Reputation: 20209

use jquery

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

Upvotes: 0

Floremin
Floremin

Reputation: 4089

Using jQuery:

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

Upvotes: 4

Related Questions