-1

Could someone tell me how to write a function: getElementsWithAttributeName("attr-name")?

It should return all elements from the current document that contain the attribute attr-name.

Also, how do I add this function to the document as well?

Any response will be much appreciated.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
anandharshan
  • 5,817
  • 4
  • 34
  • 33
  • 6
    `document.querySelectorAll('[attr-name]');` – Rob W Jan 26 '14 at 18:10
  • @RobW why are you commenting?Cant you answer directly – Zword Jan 26 '14 at 18:11
  • What have you tried so far? What was the problem that you had with your code? – Xotic750 Jan 26 '14 at 18:11
  • 1
    and [Find an element in DOM based on an attribute value](http://stackoverflow.com/q/2694640/218196) – Felix Kling Jan 26 '14 at 18:25
  • document.getElementsByAttribute = Element.prototype.getElementsByAttribute = function(attr) { var nodeList = this.getElementsByTagName('*'); var nodeArray = []; for (var i = 0, node; node = nodeList[i]; i++) { if ( node.getAttribute(attr) ) nodeArray.push(node); } return nodeArray; }; – anandharshan Jan 27 '14 at 16:00

1 Answers1

1

You can add a method to document just like this:

document.fnName = function(args){ ... };

As Rob W pointed out in the comments, you can just use the existing document.querySelectorAll() method and pass a css selector. If you really wanted this to work like getElementsByAttributeName("attr-name") you could do this:

document.getElementsByAttributeName = function(attrName){
    return document.querySelectorAll('[' + attrName+']'); 
};

Note, this is IE8+ only. (document.querySelectorAll() requires IE9 for CSS3 selectors however.)

references:

Zach Lysobey
  • 14,959
  • 20
  • 95
  • 149