向仅具有javascript / jquery和CSS的类的所有元素添加按钮/文本

时间:2019-01-24 14:17:19

标签: javascript jquery html css wordpress

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

每个框都是一个事件,该事件具有标签,也反映在一个类中,我需要做的是使所有具有特定类(在这种情况下为“免费”)的元素具有一个不可点击的小按钮或一个文本在框的右上角带有“免费”的背景,不,此框是通过插件生成的,它只是一个简码,所以我无法直接更改html,因此我尝试仅使用CSS和javascript

这是一个带有标签(名为“ tag-gratis”)的事件

<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不是函数”

2 个答案:

答案 0 :(得分:1)

我认为这里不需要使用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>

答案 1 :(得分:0)

由于document.getElementsByClassName是一个集合,因此您需要传递索引以获取元素

尝试一下

document.getElementsByClassName(".tag-gratis")