Why the element created by js has a different style with what I directly added to the html file

Jan and Feb are elements directly added to the html. Mar-Dec are elements created by js. I was wondering why the style of Jan and Feb is different from the style created by javascript.

var monthsElement = document.getElementsByClassName("months")[0]
var monthList = ["Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];
for (var month in monthList) {
    var newMonth = document.createElement("span")
    monthsElement.appendChild(newMonth)
    newMonth.setAttribute("class","month-hover")
    newMonth.innerHTML = monthList[month]
   

}
.month-hover:hover{
  
  color:#27e779 !important;
  
}

.months {
  color: #AAAAAA;
  position: relative;
  left: 350px;
  top: 90px;
  word-spacing: 10px;
}
<body>
    <div class="calendar-base">
        <div class="months">
            <span class="month-hover">Jan</span>
            <span class="month-hover">Feb</span>
            
        </div>
    </div>
</body>
Run codeHide result
+4
source share
3 answers

word-spacingis a paragraph style <p>. For this case, you will need to use either paddingor add all the text in one tag.

Hope this helps :)

var monthsElement = document.getElementsByClassName("months")[0]
var monthList = ["Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];
for (var month in monthList) {
    var newMonth = document.createElement("span")
    monthsElement.appendChild(newMonth)
    newMonth.setAttribute("class","month-hover")
    newMonth.innerHTML = monthList[month]
   

}
.month-hover:hover{
  color:#27e779 !important;
}
.month-hover{
  padding:0 7px;
}

.months {
  color: #AAAAAA;
  position: relative;
  left: 350px;
  top: 90px;
}
<body>
    <div class="calendar-base">
        <div class="months">
            <span class="month-hover">Jan</span>
            <span class="month-hover">Feb</span>
        </div>
    </div>
</body>
Run codeHide result
+3
source

If I copy the resulting HTML into notepad, it looks like this:

<div class="months">
            <span class="month-hover">Jan</span>
            <span class="month-hover">Feb</span>

        <span class="month-hover">Mar</span><span class="month-hover">Apr</span><span class="month-hover">May</span><span class="month-hover">Jun</span><span class="month-hover">Jul</span><span class="month-hover">Aug</span><span class="month-hover">Sept</span><span class="month-hover">Oct</span><span class="month-hover">Nov</span><span class="month-hover">Dec</span></div>
+2
source

This can also be done by making changes to JS

newMonth.innerHTML = monthList[month].concat(" ");
+1
source

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


All Articles