queryselector获取属性以' xxx'

时间:2017-01-12 21:31:19

标签: javascript

我正在尝试获取属性以comp-开头的所有项目。所以,请将此html作为参考:

<h1 comp-Color="red">Hello, world!</h1>
<h1 comp-Background="black">Hello, world!</h1>
<h1 comp-Age="123">Hello, world!</h1>

我尝试过这样做,但似乎没有效果:

let e = document.querySelectorAll('[^comp-]');

这样做会给我以下错误:

  

未捕获DOMException:无法执行&#39; querySelectorAll&#39;在&#39;文件&#39;:&#39; [^ comp - ]&#39;不是有效的选择器。

5 个答案:

答案 0 :(得分:2)

您可以将xpath用于此类任务

e.g。获取以xxx-开头的所有属性,使用xpath字符串

'//*/attribute::*[starts-with(name(), "xxx-")]'

attribute::的简写为@ - 这就是上面的

'//*/@*[starts-with(name(), "xxx-")]'

快速示例代码

var nodesSnapshot = document.evaluate('//*/attribute::*[starts-with(name(), "xxx-")]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var attr;
for (var i=0; i < nodesSnapshot.snapshotLength; i++ ) {
   attr = nodesSnapshot.snapshotItem(i);
   console.log(attr, attr.ownerElement) 
});

进一步阅读:XPATH on MDN

我还没有找到更详细的文档的可靠来源。除了IE之外,所有浏览器都可以使用document.evaluate,不过,我记得有一个用于IE的xpath库 - 不确定它是多么完整

google wicked good xpath

基于

javascript-xpath

答案 1 :(得分:0)

我认为你可以使用[xxx*]这就是我和其他许多人所信赖的这个神奇资源所说的:https://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048在第12位。

答案 2 :(得分:0)

不幸的是,querySelectorAll不支持部分内容。但是,有一个库dom-regex(免责声明:我写过它),就是这样做的。

它允许您使用正则表达式查询DOM。你可以像你想的那样宽松或严格。

查询整个DOM:

// Get all elements that have `comp-xxx="` in their opening tag
let e = DomRegex.all(/ comp-\w+="/i);

更便宜:

您可以提供一个选择器或一组元素来查询:

,而不是查询整个DOM
let e = DomRegex.all.against('h1', / comp-\w+="/i);

工作示例:

&#13;
&#13;
// Just include DomRegex here as a 1 liner:
!function(r,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("DomRegex",[],t):"object"==typeof exports?exports.DomRegex=t():r.DomRegex=t()}(this,function(){return function(r){function t(e){if(n[e])return n[e].exports;var o=n[e]={exports:{},id:e,loaded:!1};return r[e].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=r,t.c=n,t.p="",t(0)}([function(r,t,n){"use strict";function e(r){return"HTMLElement"in window?r&&r instanceof HTMLElement:!(!r||"object"!==("undefined"==typeof r?"undefined":d(r))||1!==r.nodeType||!r.nodeName)}function o(r){if(r instanceof RegExp)return!0;throw new TypeError("The regex parameter must be a Regular Expression")}function i(r){if(!r||"string"==typeof r)return!0;throw new TypeError("The attr parameter must be a non-empty String")}function u(r){if(e(r))return[r];if(r instanceof NodeList&&(r=Array.from(r)),Array.isArray(r))return r.filter(e);if(""!==r&&("string"==typeof r||r instanceof String))return Array.from(document.querySelectorAll(r));throw new TypeError("The first param should be a selectorOrDomNode")}function f(r){return r.outerHTML.match(/^<((?:[^>"]+|"[^"]*")+)>/)[1]}function a(r,t,n){var e=n?r.getAttribute(n):f(r);return t.test(e)}function c(r){return r?"filter":"find"}function l(r,t,n){o(t),i(n);var e=c(r);return Array.from(document.querySelectorAll("*"))[e](function(r){return a(r,t,n)})}function p(r,t,n,e){var f=u(t);o(n),i(e);var l=c(r);return f.map(function(r){return Array.from(r.querySelectorAll("*"))}).reduce(function(r,t){return r.concat(t)},[])[l](function(r){return a(r,n,e)})}function y(r,t,n,e){var f=u(t);o(n),i(e);var l=c(r);return f[l](function(r){return a(r,n,e)})}Object.defineProperty(t,"__esModule",{value:!0});var d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(r){return typeof r}:function(r){return r&&"function"==typeof Symbol&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r};n(1),n(2);var s={all:function(){for(var r=arguments.length,t=Array(r),n=0;n<r;n++)t[n]=arguments[n];return l.apply(void 0,[!0].concat(t))},one:function(){for(var r=arguments.length,t=Array(r),n=0;n<r;n++)t[n]=arguments[n];return l.apply(void 0,[!1].concat(t))}};s.all.inside=function(){for(var r=arguments.length,t=Array(r),n=0;n<r;n++)t[n]=arguments[n];return p.apply(void 0,[!0].concat(t))},s.all.against=function(){for(var r=arguments.length,t=Array(r),n=0;n<r;n++)t[n]=arguments[n];return y.apply(void 0,[!0].concat(t))},s.one.inside=function(){for(var r=arguments.length,t=Array(r),n=0;n<r;n++)t[n]=arguments[n];return p.apply(void 0,[!1].concat(t))||null},s.one.against=function(){for(var r=arguments.length,t=Array(r),n=0;n<r;n++)t[n]=arguments[n];return y.apply(void 0,[!1].concat(t))||null},t.default=s,r.exports=t.default},function(r,t){"use strict";!function(){Array.prototype.find||(Array.prototype.find=function(r){if(null==this)throw new TypeError("Array.prototype.find called on null or undefined");if("function"!=typeof r)throw new TypeError("predicate must be a function");for(var t,n=Object(this),e=n.length>>>0,o=arguments[1],i=0;i<e;i++)if(t=n[i],r.call(o,t,i,n))return t})}()},function(r,t){"use strict";Array.from||(Array.from=function(){var r=Object.prototype.toString,t=function(t){return"function"==typeof t||"[object Function]"===r.call(t)},n=function(r){var t=Number(r);return isNaN(t)?0:0!==t&&isFinite(t)?(t>0?1:-1)*Math.floor(Math.abs(t)):t},e=Math.pow(2,53)-1,o=function(r){var t=n(r);return Math.min(Math.max(t,0),e)};return function(r){var n=this,e=Object(r);if(null==r)throw new TypeError("Array.from requires an array-like object - not null or undefined");var i,u=arguments.length>1?arguments[1]:void 0;if("undefined"!=typeof u){if(!t(u))throw new TypeError("Array.from: when provided, the second argument must be a function");arguments.length>2&&(i=arguments[2])}for(var f,a=o(e.length),c=t(n)?Object(new n(a)):new Array(a),l=0;l<a;)f=e[l],u?c[l]="undefined"==typeof i?u(f,l):u.call(i,f,l):c[l]=f,l+=1;return c.length=a,c}}())}])});

// Get all elements that have `comp-xxx="` in their opening tag
let e = DomRegex.all.against('h1', / comp-\w+="/i);
console.log(e);
&#13;
<h1 comp-Color="red">Hello, world!</h1>
<h1 comp-Background="black">Hello, world!</h1>
<h1 comp-Age="123">Hello, world!</h1>
<h1>Hello World!</h1>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

使用@wordSmith,您可以执行以下操作:

Service

这意味着document.querySelectorAll("#selectId option[value*='G-']");

答案 4 :(得分:-1)

试试这个:

let e = document.querySelectorAll("[id^='comp-']");

由于我误读了这个问题,因此无效。

修改

让我建议一下:

var allH1 = document.querySelectorAll("h1");
[].forEach.call(allH1, function(d) {
    var a = [].filter.call(d.attributes, function(at) { return /^comp-/.test(at.name); });
    var attrName = a[0].name;
    var attrValue = a[0].value;
});