在HTML文档中找到一个单词,然后为该元素分配ID /类

时间:2019-03-25 23:45:16

标签: javascript html regex indexof

我正在寻找一种查找单词的方法,并根据该单词确定其所处元素的样式。我必须搜索自动生成的报告,元素和生成的报告只是很长的span标签列表,如以下代码中所缩短。报告的长度从不相同。

<html>

<head>
<meta http-equiv=Content-Type content="text/html; charset=windows-1252">
<meta name=Generator content="Microsoft Word 15 (filtered)">
</head>

<body lang=EN-US>

<div class=WordSection1>

<p class=MsoPlainText><span style='font-family:"Courier New"'>&nbsp;</span></p>

<p class=MsoPlainText><span style='font-family:"Courier New"'>Filters</span></p>

<p class=MsoPlainText><span style='font-family:"Courier New"'>                                   
Filter Name: BADDATAFILTER                                        </span></p>

<p class=MsoPlainText><span style='font-family:"Courier New"'>&nbsp;</span></p>

<p class=MsoPlainText><span style='font-family:"Courier New"'>Description</span></p>

<p class=MsoPlainText><span style='font-family:"Courier New"'>                                   
Record Type: A                                              </span></p>

<p class=MsoPlainText><span style='font-family:"Courier New"'>                                   
Description: SKIP BAD INFO                                  </span></p>

<p class=MsoPlainText><span style='font-family:"Courier New"'>&nbsp;</span></p>

<p class=MsoPlainText><span style='font-family:"Courier New"'>Conditions</span></p>

<p class=MsoPlainText><span style='font-family:"Courier New"'>                    
Condition Argument: 1 Or 2 Or 3 Or 4 Or 5 Or 6 Or 7 Or 8 Or 9 Or 10 Or 11   </span></p>
    </div>

</body>

</html>

我玩过RegExp,但不确定是否能真正帮助到我。我签出了indexOf(),我认为这是一个解决方案,但我不确定目前如何才能做到这一点。有人有主意吗?

这是我尝试使用的地方,但是此代码是错误的代码。只需发布,您就可以了解我要尝试的内容或查看我要在哪里进行此操作。

for each (i in document.body) {
  if (spans[i].text.indexOf('SKIP BAD INFO') != -1) {
console.log("string found");
//do more stuff, like get the element we found the word in to style it.
}
}

1 个答案:

答案 0 :(得分:1)

使用“ search()”方法在字符串中搜索指定值。 如果没有匹配项,它将返回-1。

//Search for 'SKIP BAD INFO'
var search = document.querySelectorAll('span');
var resultIndex = 0;
for(var i = 0; i < search.length; i++){
  if(search[i].innerText.search('SKIP BAD INFO') != -1){
    console.log('text found!');
    resultIndex = i;
  }
}

//Assign ID/Class
search[resultIndex].classList.add('className'); //Class
search[resultIndex].setAttribute('id', 'idName'); //ID

//Change CSS
search[resultIndex].style.color = red;

如果有多个结果,则将索引存储在数组中。

resultIndex = [];

//In the for loop
resultIndex.push(i);