Javascript检查HTML是否包含来自数组的项

时间:2018-06-20 19:27:51

标签: javascript html arrays

我的javascript文件中有一个潜在的html类列表

var html_list = ["blogrss",
"btnrss",
"buttonsrssfeed",
"copypasteblocker",
"facebook128x128",
"feedicon",
"iconrss",
"instagram128x128",
"jobwidget",
"pinterest128x128",
"pushnotification",
"rss128x128"]

在访问网页时,我想对数组进行迭代,如果网页包含元素之一,则简单的警报将显示该页面包含的html元素。

4 个答案:

答案 0 :(得分:1)

您将需要运行一个脚本,该脚本基本上会遍历您的列表并检查DOM以查看是否存在匹配项。请记住,selector可以是tagclassid等。在您的列表中,所有选择器都将被视为标签选择器,因此您需要提供正确的选择器,其余的将落入原位(#id.class-nametagName):

( () => {
    const elements = [
  "blogrss",
  "btnrss",
  "buttonsrssfeed",
  "copypasteblocker",
  "facebook128x128",
  "feedicon",
  "iconrss",
  "instagram128x128",
  "jobwidget",
  "pinterest128x128",
  "pushnotification",
  "rss128x128"
  ];
  const matchedElements = [];
  elements.forEach( (el) => {
    const match = document.querySelectorAll(el);
    if (match && match.length > 0) {
        matchedElements.push({ elementName: el, matches: match.length });
    }
  });
  alert(`Found ${matchedElements.length}`);
  console.log(matchedElements); // More detailed view of the matches
})();

答案 1 :(得分:0)

您可以看看jquery all选择器 https://api.jquery.com/all-selector/

答案 2 :(得分:0)

您可以使用Cheerio:https://www.npmjs.com/package/cheerio

更具体地说,请查看遍历部分:https://www.npmjs.com/package/cheerio#traversing

答案 3 :(得分:0)

您可以使用document.getElementsByTagName("*")获取所有元素,然后只需使用classListsome数组方法来确定是否有任何元素具有该类。

在下面的函数中,searchForClasses函数将根据是否匹配来返回true或false。

var html_list = [
  "testClass"
],
second_html_list = [
"banana"
]


function searchForClasses(classArray) {
  let class_included = false,
    elements = Array.from(document.getElementsByTagName("*"));
  for (let _class of classArray) {
    class_included = elements.some(ele => ele.classList.contains(_class));
    if (class_included) break;
  }
  return class_included;
}

console.log(searchForClasses(second_html_list)); // false
console.log(searchForClasses(html_list)); // true
<div class="testClass"></div>