使用JS数组突出显示特定类中的单词

时间:2017-12-28 08:52:57

标签: javascript arrays highlight word

给定特定类的div,我想突出显示包含关键字的JS数组中的单词。

例如:

  var cars = ["hello", "when", "why"];
  <p class="highlighted">How are you when</p>
  <p>How are you</p>

1 个答案:

答案 0 :(得分:0)

  

我试过但它突出了完整页面上的文字,但我想要   仅限特定班级

使用document.getElementsByClassName("highlighed"),这将返回仅具有此特定类

的htmlcollection

以下代码段可能很有用。已为说明添加了评论

var cars = ["hello", "when", "why", "are"];
//get the dom which have this specific class
var classes = document.getElementsByClassName("highlighed");
//convert collection to array to use array method
//forEach is array method
Array.prototype.slice.call(document.getElementsByClassName("highlighed")).forEach(function(item) {
  //get the innerHTML and remove whitespace and create an array from it
  var getText = item.innerHTML.trim().split(' ');
  // iterate this newly created array
  getText.forEach(function(item2, index) {
    //check if any text is matching with cars array
    if (cars.indexOf(item2) > -1) {
      // replace the element in newly created array with dom element
      getText[index] = "<span class='lightText'>" + item2 + "</span>"
    }
  });
  // create string array using join
  item.innerHTML = getText.join(' ');
})
.lightText {
  color: green;
}
<p class="highlighed">How are you when</p>
<p>How are you</p>