首页 > 解决方案 > 将按钮/文本添加到仅具有 javascript/jquery 和 css 类的所有元素

问题描述

我有一个带有这个图像框的 wordpress 网站

每个盒子都是一个事件,这个事件有标签,也反映在一个类中,我需要做的是所有具有特定类的元素(在这种情况下为“免费”)有一个不可点击的小按钮或带有背景在盒子的上角写着“免费”,不,这个盒子是用插件生成的,它只是一个简码,所以我不能直接更改 html,所以我尝试只使用 css 和 javascript

这是带有标签的单个事件(名为“标签免费”)

<article id="post-9072" class="regular post-9072 post type-post status- 
publish format-standard has-post-thumbnail category-eventos185 tag- 
culturales tag-fuera-del-barrio tag-gratis">

<div class="inner-wrap animated">

    <div class="post-content">                      





            <div class="content-inner">

                <a 
href="https://vivirenuevacba.com/museo-genaro-perez/"></a><span 
class="post-featured-img" style="background-image: 
url(https://vivirenuevacba.com/wp-content/uploads/2019/01/genaro_perez_7- 
800x589.jpg);"></span>                  




                    <div class="article-content- 
wrap">

                        <span class="meta- 
category"><a class="eventos185" 
href="https://vivirenuevacba.com/category/eventos185/">EVENTOS</a></span>                                           
                        <div class="post- 
header">

                            <h3 
class="title">


<a href="https://vivirenuevacba.com/museo-genaro-perez/">                                            
Museo Genaro Pérez                                       
</a> 

</h3>


                                <span 
class="meta-author"><span>By</span> <a 
href="https://vivirenuevacba.com/author/Vics/" title="Entradas de Vics" 
rel="author">Vics</a></span> <span class="meta-category">| <a 
href="https://vivirenuevacba.com/category/eventos185/">EVENTOS</a></span> 



</div><!--/post-header-->

                    </div><!--article-content-wrap- 
->





            </div><!--/content-inner-->


    </div><!--/post-content-->

</div><!--/inner-wrap-->

</article><!--/article-->

这是我用 css 做的一个简单按钮

.button {
margin-top: 20px;
line-height: 60px;
font-weight: bold;
padding: 0 40px;
background: salmon;
border: none;
}

这是我的javascript

document.addEventListener('DOMContentLoaded', function() {

    $(function() {
    $('.tag-gratis').each(function() {
     var button = document.createElement("button");
     button.innerHTML = "GRATIS";

     var body = document.getElementsByClassName(".tag-gratis");
     body.appendChild(button);
    });

    });
    });




</script>

现在按钮没有出现,我只是得到一个

“未捕获的 TypeError:body.appendChild 不是函数”

标签: javascriptjqueryhtmlcsswordpress

解决方案


我认为这里不需要使用 JavaScript。一个简单的伪元素就足够了。

.tag-gratis {
  position: relative;
}

.tag-gratis img {
  width: 100%;
}

.tag-gratis::after {
  content: "FREE";
  position: absolute;
  top: 20px;
  right: 20px;
  padding: 5px 10px;
  background: salmon;
  color: white;  
}
<article class="tag-gratis">
  <img src="//placehold.it/300x150">
</article>


推荐阅读