查询元素,仅属于一组类

时间:2016-12-25 11:47:26

标签: html css

document.querySelectorAll(".a, .b")返回属于a和b类的所有HTML元素的NodeList

同样,document.getElementsByClassName("a b")会返回包含相同元素的HTMLCollection

如何将这些结果缩小到那些专门属于这些类的元素:省略例如:属于a,b和c类的元素。

1 个答案:

答案 0 :(得分:1)

您可以使用:not选择器,如下所示:



var abOnly = document.querySelectorAll(".a:not(.c), .b:not(.c)");

console.log(Array.from(abOnly).map(el => el.innerText));
           

<ul>
  <li class="a b">ab</li>
  <li class="a b c">abc</li>
  <li class="a b">ab</li>
</ul>
&#13;
&#13;
&#13;

您也可以使用半查询half-js方法:

&#13;
&#13;
var hasAB = Array.from(
  document.querySelectorAll(".a, .b")
);

var noC = hasAB.filter(el => !el.classList.contains("c"));

console.log(noC.map(el => el.innerText));
&#13;
<ul>
  <li class="a b">ab</li>
  <li class="a b c">abc</li>
  <li class="a b">ab</li>
</ul>
&#13;
&#13;
&#13;

评论后编辑:&#34;更通用的方法&#34;

如何使用querySelectorAllclassList组合进行高级查询的一些示例:

&#13;
&#13;
var twoClassesAB = Array
  .from(document.querySelectorAll(".a.b"))
  .filter(el => el.classList.length === 2)
  .map(innerText)
  .join(" ");

var aOrBWithoutC = Array
  .from(document.querySelectorAll(".a, .b"))
  .filter(el => !el.classList.contains("c"))
  .map(innerText)
  .join(" ");
                                  



console.log("Only a and b, nothing else:", twoClassesAB)

console.log("At least one of a and b, explicitly not c:", aOrBWithoutC)

// Utils
function innerText(el) { return el.innerText; };
&#13;
<ul>
  <li class="a b">ab</li>
  <li class="a b c">abc</li>
  <li class="a b">ab</li>
  <li class="a b d">abd</li>
</ul>
&#13;
&#13;
&#13;