【问题标题】:Check if an array o html elements have some of the following classes [duplicate]检查数组o html元素是否具有以下某些类[重复]
【发布时间】:2016-03-12 01:44:08
【问题描述】:
// HTML

//一些Html内容

<div class=​"class--1 common-class otherClass2">​…​</div>​

// Some Html content
<div class="otherdiv"></div>

<div class=​"common-class class--2">​…​</div>​
<div class=​"common-class class--3 otherClass">​…​</div>​

// Some Html content

我正在尝试在 2 个数组之间进行迭代; 一个存储了 className,另一个存储了 html 元素

// JAVASCRIPT 
var arrayOfClasses  = ["class--5", "class--10", "class--1", "class--2"];

    var arrayOfElements = document.getElementsByClassName("common-class");
    // This return the following array
    // [<div class=​"common-class class--1">​…​</div>​, <div class=​"common-class class--2>​…​</div>​, <div class=​"common-class class--3>​…​</div>​];

我如何获得 class--1class--2false 元素的 true 值> 对于 class--3 class--5class--10

我迭代抛出arrayOfElements[i].className 使用 indexOf 后评论如下 但在这里发现了另一个问题:S

"common-class class--10".indexOf("class--1")
// Return > 13     but  i want -1 because is 10 no 1  

没有 jQuery 会更好 提前致谢。

【问题讨论】:

  • .forEach.indexOf 应该这样做。
  • @gurvinder372 谢谢!我在答案中搜索但没有找到但这只是返回巧合,我如何得到其他值的错误?

标签: javascript arrays for-loop comparison


【解决方案1】:

var array1 = ["Hello", 5, "Hola", 27, 'otherValue'];
var array2 = [27, "Hello"];

var intersection = [];

var intersectionObj = {};

for(var i=0; i<array1.length; i++) {
  if(array2.indexOf(array1[i]) > -1) {
    intersection.push(array1[i]);
  }
}
alert(intersection);
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  
</body>
</html>

【讨论】:

    猜你喜欢
    • 2010-10-20
    • 1970-01-01
    • 2016-06-07
    • 2023-02-02
    • 2016-09-09
    • 2013-09-20
    • 2022-01-04
    • 2017-12-19
    • 2011-07-11
    相关资源
    最近更新 更多