avinash majhi avinash majhi - 9 days ago 6
Node.js Question

get child node in javascript

how to change the color of ABCD inside "sm" through node method.

HTML



</html>
<body>
<div class="row">
<div class="firstMain"><div class="sm">ABCD</div></div>
<div class="secondMain"><div class="sm">XYZ</div></div>
</div>
</body>
</html>


Javascript

var mp , sb ;
mp = document.getElementsByClassName('main')[0];
sb = document.getElementsByClassName('sm')[0];
if ( sb.firstChild === mp ){
sb.style.color = "blue";
}


I want to change the color of class "sm" differently in different div like color of "sm" (firstMain) will be different from class "sm" (secondMain)

A.J A.J
Answer

Have color array and select items iterate over them and set color.

**This will be handy if there are a lot a sm div's

Working Snippet:

var sms = document.getElementsByClassName("sm");
var colors = ["red", "blue"];
for (var i = 0; i < sms.length; i++) {
  sms[i].style.color = colors[i];
}
<div class="row">
  <div class="firstMain">
    <div class="sm">ABCD</div>
  </div>
  <div class="secondMain">
    <div class="sm">XYZ</div>
  </div>
</div>