Setting a new class in a div

Possible duplicate:
Change element CSS class using JavaScript

I am trying to set div attributes using this script. And I have a problem in the third line, where I try to get divs from the parent div whose id is "loading". but here is the problem, it looks like there is nothing in the divs variables. Why is that?

Script:

function blink() { document.getElementById("loading").setAttribute("class","loader"); var divs = document.getElementById("loading").getElementsByTagName("div"); alert(divs[0].class); for(var i=0;i<divs.length;i++) { var _id = divs[i].id; document.getElementById(divs[i].id).setAttribute("class", "bar"); } } 

HTML:

  <div id="loading" class="loader2"> <a href="#" onClick="blink()"> <div class="bar_"></div> <div class="bar_"></div> <div class="bar_"></div></a> </div> 

I want to replace the divs: "bar_" class with "bar". what am i trying to do.

+6
source share
2 answers
  • class is the future reserved word in JavaScript. Use className , not class .
  • Usually use properties, not setAttribute
  • There is no need to retrieve <div> by id when you already have them in divs !

So:

 function blink() { var loader = document.getElementById("loading"); loader.className = "loader"; var divs = loader.getElementsByTagName("div"); for(var i=0; i<divs.length; i++) { divs[i].className = "bar"; } } 
+22
source

Inserting a div inside an a tag is invalid html, which does not help. But the main problems are that you need to use el.className to read the class attribute. Also, you are trying to read the id attribute for your inner divs if you have not defined it in html.

0
source

Source: https://habr.com/ru/post/909198/


All Articles