Eman Eman - 6 months ago 21
Javascript Question

JavaScript strange behavior when set a class by setAttribute

I want to set a specific class on some of the lines of my html code by JS.
On the output I have four lines and lines 1 and 2 and 4 (which started with Arabic characters) should be affected and get a red background. But it's strange why isn't second line affected by the class. Is there something wrong I did?

<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>This is</title>
<style> .rtl {background: red;}</style>
</head>


<body>

<div class="chat-item__text">سلام</div>

<div class="chat-item__text">بله</div>

<div class="chat-item__text">koo</div>

<div class="chat-item__text">اینور</div>

<script>


function checkRtl( character )
{
var RTL = ['ا','ب','پ','ت','س','ج','چ','ح','خ','د','ذ','ر','ز','ژ','س','ش','ص','ض','ط','ظ','ع','غ','ف','ق','ک','گ','ل','م','ن','و','ه','ی'];
if( RTL.indexOf( character ) > -1)
{
return true;
} else
{
return false;
}

}

function init()
{
var chatText = document.getElementsByClassName("chat-item__text");
for (var i = 0; i < chatText.length; i++)
{
var eachLine = chatText[i].innerHTML;
var firstChar = eachLine.charAt(0);
console.log(firstChar);
if (checkRtl(firstChar))
{
chatText[i].setAttribute("class", "rtl");
}

}
}
window.onload = init;
</script>
</body>
</html>


Thanks in advance.

Answer

Use Element.classList.add() instead of setAttribute()

function checkRtl(character) {
  var RTL = ['ا', 'ب', 'پ', 'ت', 'س', 'ج', 'چ', 'ح', 'خ', 'د', 'ذ', 'ر', 'ز', 'ژ', 'س', 'ش', 'ص', 'ض', 'ط', 'ظ', 'ع', 'غ', 'ف', 'ق', 'ک', 'گ', 'ل', 'م', 'ن', 'و', 'ه', 'ی'];
  if (RTL.indexOf(character) > -1) {
    return true;
  } else {
    return false;
  }

}

function init() {
  var chatText = document.getElementsByClassName("chat-item__text");
  for (var i = 0; i < chatText.length; i++) {
    var eachLine = chatText[i].innerHTML;
    var firstChar = eachLine.charAt(0);
    console.log(firstChar);
    if (checkRtl(firstChar)) {
      chatText[i].classList.add('rtl');
      //chatText[i].setAttribute("class", "rtl");
    }

  }
}
window.onload = init;
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>This is</title>
  <style>
    .rtl {
      background: red;
    }
  </style>
</head>


<body>

  <div class="chat-item__text">سلام</div>

  <div class="chat-item__text">بله</div>

  <div class="chat-item__text">koo</div>

  <div class="chat-item__text">اینور</div>

</body>

</html>