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
3 Answers
Reset to default 6Working 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>
本文标签:
版权声明:本文标题:javascript - How to set text strikethrough to all element with the same class after onclick event? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741300794a2371079.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论