admin管理员组

文章数量:1279043

I have this HTML:

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

And this is my JS:

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

How do I change the text to be strikethrough after I pressed the button?

Fiddle

Note: I'm looking for vanilla JS approach. Not jQuery way.

I have this HTML:

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

And this is my JS:

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

How do I change the text to be strikethrough after I pressed the button?

Fiddle

Note: I'm looking for vanilla JS approach. Not jQuery way.

Share Improve this question asked Aug 12, 2015 at 10:48 Zulhilmi ZainudinZulhilmi Zainudin 9,36513 gold badges68 silver badges102 bronze badges 1
  • 2 jsfiddle/arunpjohny/jqa7xjmf/1 – Arun P Johny Commented Aug 12, 2015 at 10:51
Add a ment  | 

3 Answers 3

Reset to default 6

Working JSFiddle

https://jsfiddle/jqa7xjmf/2/

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

ele is an array, so you should change each element by itself

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

As document.getElementsByClassName returns an array-like object of all child elements which have all of the given class names. You need to use for loop it iterate the elements returned by it.

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

DEMO

<script>
    function hello() {
         // Get elements with class 'myclass'.
         var ele = document.getElementsByClassName("myclass");

         // Add the strikethrough to all those elements.
         for (let i = 0; i < ele.length; i++) { 
             ele[i].style.textDecoration = "line-through";
         }    
     }
</script>

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

本文标签: