使用querySelectorAll排除标签标签

时间:2018-09-11 13:51:09

标签: javascript html css

下面是标签。

final QuerySnapshot querySnapshot = 
  await Firestore.instance.collection('cakes').getDocuments();
final List<DocumentSnapshot> documents = 
  querySnapshot.documents.where((snapshot) => snapshot.data.containsValue('cheesecake'));
// now the [documents] object will only contain documents, which have "cheesecake" as any of their fields

它嵌套在以下结构中(请参见最后的标签):

<label style="vertical-align: middle; cursor: pointer;">Terrain</label>

问题: 我想将此标签与另一个<div class="event-section"> <div class="googlemaps"> <div id="googleMap6512"> <div> <div class="gm-style"> <div class="gmnoprint"> <div class="gm-style-mtc"> <div> <div> <label>... 中的标签一起排除在Javascript中,我在这里尝试过:

div.widget_small

这不起作用。我认为我选择了错误的选择器,或者……?

3 个答案:

答案 0 :(得分:1)

类不是继承的。

void main()不是labelgooglemaps的成员,因此widget_small确实与之匹配。

您需要选择一个标签,其中没有一个祖先是这些类的成员。

没有方法可以在选择器中表达它,因此您需要选择所有label:not(.googlemaps):not(.widget_small)元素,然后对其进行循环过滤,以过滤出具有那些类别之一的祖先的那些(您可以通过递归循环来确定)重复label,直到找到与.parentNode(失败)或.googlemaps, .widget_small(成功)匹配的匹配项。

或者,您可能可以非常精确地确定元素具有哪些祖先:

body

...但是维护起来可能会麻烦得多。

答案 1 :(得分:0)

在您的代码中:

var arrInp = document.querySelectorAll("label:not(.googlemaps):not(.widget_small)");

选择器部分获取所有label.googlemaps类的所有.widget_small

请参见对:not选择器的参考:MDN web docs :not()

要实现解决方案,请考虑@Quentin的声明。

更新

也许。这样就是您所需要的,例如上面提到的@ChrisLi?

var arrInp = document.querySelectorAll(".event-section > div:not(.googlemaps):not(.widget_small) label");

答案 2 :(得分:0)

使用JavaScript的相对简单的方法如下:

// converting the resulting iterable into an Array:
Array.from(
  // using document.querySelectorAll() to retrieve
  // a NodeList of all <label> elements in the
  // document:
  document.querySelectorAll('label')

  // filtering that Array of <label> elements with
  // Array.prototype.filter():
).filter(
  // using an Arrow function to filter the Array elements:
  // 'el' is a reference to the current Array element,
  // here we find the closest ancestor element which
  // matches the supplied selector; coupled with the NOT
  // (!) operator to invert the 'truthiness' of the result,
  // therefore if closest() returns null (no element was
  // found) we convert that to true; thereby keeping the
  // Array elements with no matching ancestors:
  (el) => !el.closest('.demo, .test')

  // iterating over the resulting Array using
  // Array.prototype.forEach():
).forEach(
  // with another Arrow function, here we use the
  // Element.classList API to add a class, in this
  // instance just to demonstrate which element(s)
  // were found:
  (label) => label.classList.add('orange')
);
.orange {
  color: #f90;
}
<div class="demo"><label for="">label 1<input type="text"></label></div>
<div class="test"><label for="">label 1<input type="text"></label></div>
<label for="">label 1<input type="text"></label>

参考文献: