首页 > 解决方案 > 添加 REL 属性和附加 CLASS 属性的 Javascript 代码

问题描述

我正在寻找一些 Javascript 代码,它们会将 REL 属性添加到 A 链接元素中,然后将 CLASS 属性附加到其中的 Button 元素中。

<table>
<tbody>
<tr>
<td class="column-main">
Sample Text Here
</td>
<td class="column-url">
<a href="website.com"><button class="classNamehere">View</button></a>
</td>
</tr>
</tbody>
</table>

我想要目标 A 链接和其中的 Button 元素,以便将其更改为:

<a href="website.com" rel="iLightbox" ><button class="classNamehere fusion-lightbox-link">View</button></a>

这是我尝试过的...

$('.column-url a').attr( 'rel', 'iLightbox' );
$('.column-url button').attr( 'class', 'fusion-lightbox-link' );

标签: javascriptwordpress

解决方案


以下是三个示例,它们以不同的方式实现您想要的效果:

    // This code would be the code working for your example, only get one element and apply the new attribute and class to id 
    var tableTd = window.getElementsByClassName('column-url')[0],
        aLink = tableTd.getElementsbyTagName('a')[0],
        aButton = aLink.getElementsbyTagName('button')[0];

        aLink.setAttribute('rel', 'iLightbox');
        aButton.classList.add('fusion-lightbox-link');

    // This would work if you have the link and button inside a specific container (td for example)
    var container = window.getElementsByClassName('column-url');

    for( var i = 0; i < tableTd.length, i++)[
        container[i].getElementsbyTagName('a')[0].setAttribute('rel', 'iLightbox');
        container[i].getElementsbyTagName('a')[0].getElementsbyTagName('button')[0].classList.add('fusion-lightbox-link');
    }

    // This would look for all A tags with specific class name and set rel attribute to id, then find the button and add a class to it
    var aLinks = window.getElementsByClassName('aClassName');
    for( var i = 0; i < aLinks.length, i++)[
        aLinks[i].setAttribute('rel', 'iLightbox');
        aLinks[i].getElementsbyTagName('button')[0].classList.add('fusion-lightbox-link');
    }

推荐阅读