Abdennour TOUMI Abdennour TOUMI - 1 year ago 89
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

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 :


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

Answer Source

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) {
  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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download