如何在onclick事件后将文本删除线设置为具有相同类的所有元素?

时间:2015-08-12 10:48:45

标签: javascript html css

我有这个HTML:

<button onclick="hello()">Click Me</button>
<p class="myelement">Hello world 1</p>
<p class="myelement">Hello world 2</p>

这是我的JS:

function hello(){
    alert('hello!');
    var ele = document.getElementsByClassName("myelement");
    ele.style.setProperty("text-decoration", "line-through");
}

按下按钮后,如何将文字更改为删除线?

Fiddle

注意:我正在寻找vanilla JS方法。不是jQuery方式。

3 个答案:

答案 0 :(得分:5)

使用JSFiddle

https://jsfiddle.net/jqa7xjmf/2/

for (var i in ele)
    ele[i].style.textDecoration='line-through'

ele是一个数组,所以你应该自己更改每个元素

&#13;
&#13;
function hello(){
    var ele = document.getElementsByClassName("myelement");
    for (var i in ele)
	ele[i].style.textDecoration='line-through'
    
}
&#13;
<button onclick="hello()">Click Me</button>
<p class="myelement">Hello world 1</p>
<p class="myelement">Hello world 2</p>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

由于document.getElementsByClassName返回具有所有给定类名的所有子元素的类数组对象。你需要使用for循环迭代它返回的元素。

var ele = document.getElementsByClassName("myelement");
for(var i=0;i<ele.length;i++){
    ele[i].style.setProperty("text-decoration", "line-through");
}

DEMO

答案 2 :(得分:1)

<script>
    function hello()
       {
    var ele = document.getElementsByClassName("myelement");

    for (i = 0; i < ele.length; i++) { 
    ele[i].style.textDecoration = "line-through";
      }

                             }
</script>
<button onclick="hello()">Click Me</button>
<p class="myelement">Hello world 1</p>
<p class="myelement">Hello world 2</p>