1

I'm trying to apply the onclick event with JavaScript to the following elements:

<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>

If I click on the first element (with index [0]) then this works, but I need this event applicable for all classes:

document.getElementsByClassName('abc')[0].onclick="function(){fun1();}";
function  fun1(){
document.getElementsByClassName('abc').style.color="red"; 
}

3 Answers 3

1

.onclick does not expect to receive a string, and in fact you don't need an extra function at all.

However, to assign it to each element, use a loop, like I'm sure you must have learned about in a beginner tutorial.

var els = document.getElementsByClassName('abc');
for (var i = 0; i < els.length; i++) {
  els[i].onclick = fun1;
}

function fun1() {
  this.style.color = "red";
}
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>

Sign up to request clarification or add additional context in comments.

1 Comment

thanks i really forget to index my class in for loop
0

To expand on the solution provided by @rock star I added two small additions to the function. First it is better to add / reemove a class (with an associated style rule) to an element than directly applying the stylerule to the element.

Secondly - on the click event - this will now remove the red class (and therefore style) from the previously selected element and add it to the new element. This will allow only one element to be red at a time (in the original solution any element that was clicked would become red).

var els = document.getElementsByClassName('abc');
for (var i = 0; i < els.length; i++) {
  els[i].onclick = fun1;
}

function fun1() {
  var oldLink = document.getElementsByClassName('red')[0];
  if(oldLink) {oldLink.classList.remove('red')};
  this.classList.add('red');
}
.red {
 color:red;
}
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>

Comments

0

This works:

<body>
<div class="abc">first</div>
<div class="abc">second</div>
<div class="abc">third</div>
<script>
var elements = document.getElementsByClassName('abc');

for(var i = 0, max = elements.length; i < max; i += 1) {
  var clickedElement = elements[i];
  clickedElement.onclick=function (){
    fun1(this);
  };
}

function  fun1(element){
  element.style.color="red"; 
}
</script>
</body>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.