zxc34 zxc34 - 15 days ago 5
CSS Question

addClass and className does not work in js

hr1
is the id of a line which dynamically created using JavaScript. Then I tried to set the color of its
bottom border
. When I run the code, I find that version 1 works but version2, version 3, version 4 and version 5 doesn't work. Hope someone could help me point out why this happens. Thank you in advance.

Version 1:

$('#hr' + 1).css("border-bottom-color", "red");


version 2:

js:
$('#hr' + 1).addClass('thing');

css:
.thing {
border-bottom-color: red;
}


version 3:

js:
$('#hr' + 1).className = "thing";

css:
.thing {
border-bottom-color: red;
}


version 4:

js:
$('#hr' + 1).attr('class', "thing");

css:
.thing {
border-bottom-color: red;
}


version 5:

js:
$('#hr' + 1).setAttribute('class', "thing");

css:
.thing {
border-bottom-color: red;
}

Answer

Number 2 should work, so it's probably your CSS that doesn't apply (or .thing is overridden by some other css rule). Try to make your selector .thing more specific.

.hr {
  height: 2px;
  border-bottom: 1px solid #000;
  margin: 0 0 10px;
}

.thing {
  border-bottom-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hr1" class="hr"></div>
<div id="hr2" class="hr"></div>
<div id="hr3" class="hr"></div>
<button onClick='$("#hr1").addClass("thing")'>Change color</button>