最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - plain js to select element by attribute name starts with - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited May 23, 2017 at 10:29 CommunityBot 11 silver badge asked Sep 8, 2016 at 8:21 Abdennour TOUMIAbdennour TOUMI 93.3k42 gold badges267 silver badges269 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 7

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>

ES6 solution :

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

Then :

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

versions of 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

or :

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

So I bined the efforts of gavgrif and mplungjan with what I made already:

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

Necromancing.

ES 5 solution :

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

Then :

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

div [^="ng-"] should do it for you - What this does is specificy all elements that have attributes that start with "ng-" (and in his example applies a background color)

*[^="ng-"] {background-color:red}
发布评论

评论列表(0)

  1. 暂无评论