用于按属性名称选择元素的普通js以

时间:2016-09-08 08:21:48

标签: javascript regex selector built-in

上下文:

  • HTML

     <div ng-me=""></div>
     <div ng-you=""></div>
      <p ng-you=""></p>
    

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

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

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

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

  3. 然而,第一个使用jQuery,第二个解决删除问题已选定元素 NOT 选择

    我试试这个:

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

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

5 个答案:

答案 0 :(得分:4)

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

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

&#13;
&#13;
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
&#13;
<div ng-a="a">a</div>
<div ng-b="b">b</div>
<p ng-c="c">c</p>
&#13;
&#13;
&#13;

答案 1 :(得分:4)

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

答案 2 :(得分:2)

所以我将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

答案 3 :(得分:1)

div [^ =&#34; ng - &#34;]应该为你做什么 - 这样做具体是所有具有以&#34; ng - &#34;开头的属性的元素。 (在他的例子中应用背景颜色)

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

答案 4 :(得分:0)

Necromancing。

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-"));