如何为没有ID的元素替换类名

How to replace class name for element without ID?

本文关键字:元素 替换 ID      更新时间:2023-09-26

Pure JS请:你好本线程:如何在JavaScript中按类获取元素?包含我问题的起点。如何替换类名本身?使用上面链接中的例子,我似乎无法让它发挥作用。这是我的jsFiddle:

非常感谢!

<div class="ggg">blavlavbla </div>
function replaceClass()
{
   var plusLinks = document.querySelectorAll('ggg');
   var firstLink = plusLinks[0];
   firstLink.setAttribute('class', 'aw-top-content-mod');
}
replaceClass();

只需将.添加到类名:

   function replaceClass()
             {
                 var plusLinks = document.querySelectorAll('.ggg');
                 var firstLink = plusLinks[0];
                 firstLink.setAttribute('class', 'aw-top-content-mod');
             }
     replaceClass();

JSFiddle

您可以使用getElementsByClassName而不是具有更多浏览器支持的querySelectorAll。你可以随心所欲。

function replaceClass()
{
    var firstLink = document.getElementsByClassName('ggg')[0];
    firstLink.setAttribute('class', 'aw-top-content-mod');
}
        
 replaceClass();
.aw-top-content-mod
{
    color:red;
}
<div class="ggg">blavlavbla </div>