纯 js 到 select 元素按属性名称开头

plain js to select element by attribute name starts with

上下文:

我想 select 所有属性名称以 ng- 开头的元素。


使用 jQuery,以下链接是最接近此问题的线程:

  1. jQuery - How to select value by attribute name starts with .

  2. How to remove all Attributes by attribute name starts with .

但是,第一个使用 jQuery,第二个解决 删除 已经 selected 元素的问题 不是 selection .

我试试这个:

document.querySelectorAll('[ng-*]')

它不起作用,而是抛出错误。

这里我使用 querySelectorAll 来获取我想要检查的所有对象。

然后我查看每个返回对象的属性集合

ES6+

const attrStartsWith = (sel,str) => [...document.querySelectorAll(sel)]
  .filter(ele => [...ele.attributes]
    .filter(({name}) => name.startsWith(str))
    .length>0
  )

console.log(attrStartsWith("*","ng")); // all
console.log(attrStartsWith("div","ng")); // divs
<div ng-a="a">a</div>
<div ng-b="b">b</div>
<p ng-c="c">c</p>

ES5 及更低版本

function attrStartsWith(sel,str) {
  var el = document.querySelectorAll(sel), res=[];
  
  for (var i = 0, n=el.length; i < n; i++){
    for (var j=0;j<el[i].attributes.length;j++) {
      if (el[i].attributes[j].name.indexOf(str)==0) {
        res.push(el[i]); 
      }
    }
  }
  return res;
}
console.log(attrStartsWith("*","ng")); // all
console.log(attrStartsWith("div","ng")); // divs
<div ng-a="a">a</div>
<div ng-b="b">b</div>
<p ng-c="c">c</p>

div [^="ng-"] 应该为你做 - 它所做的是具体所有具有以 "ng-" 开头的属性的元素(并且在他的示例中应用了背景色)

*[^="ng-"] {background-color:red}

所以我将 gavgrif 和 mplungjan 的努力与我已经做的结合起来:

HTML:

 <div ng-me="">1</div>
 <div ng-you="">2</div>
 <div not-me="">3</div>
 <div ng-yes="">4</div>

CSS:

.ng-class {
    background-color: red;
}

JavaScript:

var el = document.getElementsByTagName("*");
var list = [];

// Grab all elements on the page and check them for attributes
for (var i = 0, n = el.length; i < n; i++) {
     for (var j = 0; j < el[i].attributes.length; j++) {
        // If match, push into seperate array
        if (el[i].attributes[j].name.indexOf("ng") == 0)       
            list.push(el[i]);
     }
}

// Add a custom class to these elements
for(var i = 0; i < list.length; i++) {
    list[i].classList.add('ng-class');
}

Codepen example here

ES6 解决方案:

const attrStartsWith = (prefix) =>
  Array.from(document.querySelectorAll('*'))
   .filter(
      (e) => Array.from(e.attributes).filter(
        ({name, value}) => name.startsWith(prefix)).length
   )

然后:

attrStartsWith('ng-') // return an array of HTML elements which  have attributes name starts with "ng-"

2017-12-02 的版本

const queryByAttrNameStartsWith = (contextualSelector = '*') => {
  const elements = Array.from(document.querySelectorAll(contextualSelector));
  return (prefix) =>
    elements.filter(e =>
      Array.from(e.attributes).find(({ name, value }) =>
        name.startsWith(prefix)
      )
    );
};
//then
queryByAttrNameStartsWith('*')('data-'); // all elements that have attribute name that starts with 'data-'
queryByAttrNameStartsWith('div')('ng-'); // ony DIV elements that have attribute name that starts with 'ng-'
//.. so on

或:

NodeList.prototype.filterByAttrNameStartsWith = function(prefix) {
  return Array.from(this).filter(e =>
    Array.from(e.attributes).find(({ name, value }) => name.startsWith(prefix))
  );
};
//then
document.querySelectorAll('*')
 .filterByAttrNameStartsWith('data-'); // all elements that have attribute name that starts with 'data-'
document.querySelectorAll('div')
 .filterByAttrNameStartsWith('ng-'); // ony DIV elements that have attribute name that starts with 'ng-'
//.. so on

死灵法术。

ES 5 解决方案:

    function findElementsWithArributePrefix(selector, prefix)
    {
        return [].slice.call(document.querySelectorAll(selector)).filter(function (e)
        {
            return [].slice.call(e.attributes).filter(
                function (attr)
                {
                    return attr.name.startsWith(prefix);
                }
            ).length;
        });
    }

然后:

console.log("prfx", findElementsWithArributePrefix("*", "ng-"));