Search code examples
javascriptregexselectorbuilt-in

plain js to select element by attribute name starts with


Context :

  • HTML

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

I want to select all elements which has attribute name starts with ng-.


Using jQuery , the following links are the closest threads to this issue :

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

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

However ,the first uses jQuery , and the second resolves removing issue of already selected elements NOT selection .

I try this :

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

And it does not work , but rather, it throws error.


Solution

  • Here I use querySelectorAll to get all objects that I want to check.

    Then I look at the attributes collection of each returned object

    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 and lower

    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>