Abdennour TOUMI Abdennour TOUMI - 3 months ago 12
Javascript Question

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.

Answer

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

Then I look at the attributes collection of each returned object

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>