简体   繁体   English

使用查询选择器获取以特定innerHTML开头的所有元素?

[英]Get all the elements that start with a particular innerHTML using query selector?

I am currently having problem with selecting and matching the innerHTML using querySelectorAll. 我目前在使用querySelectorAll选择和匹配innerHTML时遇到问题。

Here is what i did: 这是我所做的:

document.querySelectorAll('*[class^="js-display-url"]').contains('product')

What the html is: 什么是html:

<span class="js-display-url">product/poss/newslanges</span>

But i want to match the class js-display-url starting with product but can't do that. 但是我想匹配以产品开头的js-display-url类,但是不能这样做。 please help. 请帮忙。

With DOM selectors you cannot select elements based on the inner HTML, but you can loop through all the elements with that class and single out the ones that match your condition: 使用DOM选择器,您不能选择基于内部HTML的元素,但是可以遍历该类的所有元素,并挑选出符合条件的元素:

var allElements = document.querySelectorAll('*[class^="js-display-url"]');
var myElements = [];

for (var i = 0; i < allElements.length; i++) { 
    if (allElements[i].innerHTML.startsWith('product')) {
        myElements.push(allElements[i]);
    }
}

There isn't a DOM selector which will filter based on text nodes, but you can filter using some array methods, since a NodeList is array-like. 没有DOM选择器可根据文本节点进行过滤,但是您可以使用某些数组方法进行过滤,因为NodeList类似于数组。

In particular, Array.prototype.filter can get the elements that meet your criteria. 特别是, Array.prototype.filter可以获取满足您条件的元素。

 var filter = Array.prototype.filter; var allElements = document.querySelectorAll('.js-display-url'); var productElements = filter.call(allElements, function(element) { return element.innerText.startsWith('product'); }); console.log(productElements); 
 <span class="js-display-url">product/poss/newslanges</span> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM