如何使用Javascript将一个类添加到div的内部HTML?

时间:2022-10-30 09:41:54

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

我正在尝试解决Wordpress看似不可能的自定义问题。这是<?php the_category();?>打印出来的:

<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!

到目前为止,我只找到了为具有现有ID或类的元素分配其他类的方法。在此先感谢您的帮助!

3 个解决方案

#1


4  

Using jQuery:

使用jQuery:

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

#2


3  

Since the title says Using JavaScript

由于标题说使用JavaScript

Try this for a JavaScript solution:

试试这个JavaScript解决方案:

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:

或者,如果你和孩子们在一起,你可以使用jQuery,你可以这样做:

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

#3


0  

use jquery

使用jquery

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

#1


4  

Using jQuery:

使用jQuery:

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

#2


3  

Since the title says Using JavaScript

由于标题说使用JavaScript

Try this for a JavaScript solution:

试试这个JavaScript解决方案:

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:

或者,如果你和孩子们在一起,你可以使用jQuery,你可以这样做:

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

#3


0  

use jquery

使用jquery

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