0

I'm doing something like 'to do list'. I want to strike out text on the task but it didn't work so i tried wtih background color or something. `

for(var i=0; i<document.getElementsByClassName('task').length; i++){
    document.getElementsByClassName('task')[i].onclick = function(){
        this.parentElement.backgroundColor = 'pink';
    }
}`

Before that I'm creating new element which have 'task' class. Someone know what am i doing wrong?

szpanel
  • 35
  • 1
  • 6

2 Answers2

1

So it must be parentNode and you need to amend element's style. Also I would recommend to use addEventListener, as it's the most reliable way to bind events to elements.

var tasks = document.getElementsByClassName('task');
for (var i = 0, len = tasks.length; i < len; i++) {
  tasks[i].addEventListener('click', function() {
    this.parentNode.style.backgroundColor = 'pink';
  }, false);
}
.task { cursor: pointer; }
<ul>
  <li><span class="task">Task 1</span></li>
  <li><span class="task">Task 2</span></li>
  <li><span class="task">Task 3</span></li>
  <li><span class="task">Task 4</span></li>
  <li><span class="task">Task 5</span></li>
</ul>
VisioN
  • 132,029
  • 27
  • 254
  • 262
  • 1
    @szpanel If you click on *Run code snippet* above and test it, you will see that it works. – VisioN Feb 15 '18 at 15:26
  • Yes i know. I see it but on my webpage it doesnt work. Can you check my code? https://pastebin.com/WhpvjdV0 – szpanel Feb 15 '18 at 15:27
  • Maybe it's because i have background-color in css? – szpanel Feb 15 '18 at 15:29
  • If you already use jQuery, you should use some jQuery functions. – NoobTW Feb 15 '18 at 15:29
  • Im new in javascript and jquery so at this moment i want to understand it just in js – szpanel Feb 15 '18 at 15:30
  • 1
    @szpanel It doesn't work because you first bind `click` event to all `.task` elements and then you add these elements dynamically. You should either bind event to the element right after its was inserted in the DOM or use [delegated event binding](https://stackoverflow.com/a/1688293/1249581). – VisioN Feb 15 '18 at 15:32
  • It will be difficult, as you could see my english is bad and im new in this so.. XD but thank you so much i will read it and try do something – szpanel Feb 15 '18 at 15:36
0

How about this.style?

for(var i=0; i<document.getElementsByClassName('task').length; i++){
    document.getElementsByClassName('task')[i].onclick = function(){
        this.style.backgroundColor = 'pink';
    }
}

https://codepen.io/anon/pen/rJGXNr

NoobTW
  • 2,017
  • 2
  • 19
  • 35