检查第(n)个元素是否包含类名

check if (n)th elements contain class name

本文关键字:元素 是否 包含类 检查      更新时间:2023-09-26

如何检查前3个li元素是否包含类yes?然后,执行一个函数。只有香草Js,没有jquery。

<ul>
  <li class="yes">blah blah</li>
  <li class="yes">blah blah</li>
  <li class="yes">blah blah</li>
  <li class="no">blah blah</li>
  <li class="no">blah blah</li>
  <li class="yes">blah blah</li>
  <li class="yes">blah blah</li>
</ul>

示例逻辑:

if (li[0] && li[1] && li[2] has class = yes) {
    alert("You win!");
}
else{
    alert("You lose!");
}   

除了几个很棒的javascript解决方案外,我还将提出两个面向CSS的选项。

1)。第n个孩子。您可以使用:nth-child尝试这种方法来选择前三个子项:

var li = document.querySelectorAll('ul li.yes:nth-child(-n+3)');
if (li.length === 3) {
    // all three first elements has class "yes"
}

其思想是li.yes将选择类为"yes"的元素,而:nth-child(-n+3)确保返回的元素仅为前三个。结果是这两个条件的乘积。然后我们只需要检查返回的结果的长度是否为3。

演示:http://jsfiddle.net/b1oy0d6w/

2)。同级选择器。或者还有一个有点疯狂的版本,但使用同级选择器+:会更短

if (document.querySelector('ul li.yes:first-child + .yes + .yes')) {
    // all three first elements has class "yes"
}

这种方法背后的理念:

  1. li.yes:第一个子-检查第一个li是否具有类"yes"
  2. 下一个元素具有类"yes"
  3. 第二个(即第三个)元素之后的下一个元素也具有类"yes"

仅当满足上述三个条件时,整个选择器ul li.yes:first-child + .yes + .yes才返回第三个li元素。

演示:http://jsfiddle.net/b1oy0d6w/1/

一种方法:

// storing an Array of the first three <li> elements returned by
// document.querySelectorAll():
var firstThree = [].slice.call(document.querySelectorAll('li'), 0, 3);
// logging whether or not every (using Array.prototype.every())
// Array element's classList contains the class of 'yes':
console.log(firstThree.every(function(el) {
  return el.classList.contains('yes');
}));

var firstThree = [].slice.call(document.querySelectorAll('li'), 0, 3);
console.log(firstThree.every(function(el) {
  return el.classList.contains('yes');
}));
<ul>
  <li class="yes">blah blah</li>
  <li class="yes">blah blah</li>
  <li class="yes">blah blah</li>
  <li class="no">blah blah</li>
  <li class="no">blah blah</li>
  <li class="yes">blah blah</li>
  <li class="yes">blah blah</li>
</ul>

参考文献:

  • Array.prototype.every()
  • Array.prototype.slice()
  • CCD_ 10
  • CCD_ 11

不应该太难,试试:

var answer = true
var lis = document.querySelectorAll("ul > li") // Gets all the <lis> in all the uls
var classes = lis.map(function (e) {return e.className} //list of classnames
for (e in classes.splice(0,3)) { // runs a function on each of the first 3 elements
    answer = (e == "yes") && answer // if any of the elements isnt "yes", answer will become false
}
if (answer) {
    alert("You win!!!!!!!")
} else {
    alert("You lose")
}

id="ul"添加到UL元素,然后运行:

var el=document.getElementById('ul');
var li=el.getElementsByTagName('li');
if(
/ yes /.test(' '+li[0].className+' ')&&
/ yes /.test(' '+li[1].className+' ')&&
/ yes /.test(' '+li[2].className+' ')
){
alert('you win');
}else{
    alert("You lose!");
}

http://jsfiddle.net/k9sev1hq/