Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for setting attributes with an object #53

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,17 @@ var url = dom('img').attr('src');
dom('img').attr('src', 'image/of/maru.jpg');
```

### .attr(obj)

Set attributes with an object

```js
dom('a').attr({
href : 'http://github.com',
rel : 'source'
});
```

### .ATTR()

Attribute getters. These are functionally equivalent
Expand Down
9 changes: 9 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,15 @@ List.prototype.remove = function(){
*/

List.prototype.attr = function(name, val){

// set via object
if ("object" == typeof name){
for (var attr in name) {
this.attr(attr, name[attr]);
}
return this;
}

// get
if (1 == arguments.length) {
return this.els[0] && this.els[0].getAttribute(name);
Expand Down
19 changes: 19 additions & 0 deletions test/dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,25 @@ describe('.attr()', function(){
assert('logo' == list.attr('id'));
})
})

describe('with an object of key value pairs', function(){
it('should set the attributes', function(){
var list = dom('<div><a></a><a></a></div>').find('a');
var ret = list.attr({ href : '#', rel : 'rels/attr-test'});
assert(ret == list);
assert('#' == list.get(0).getAttribute('href'));
assert('#' == list.get(1).getAttribute('href'));
assert('rels/attr-test' == list.get(0).getAttribute('rel'));
assert('rels/attr-test' == list.get(1).getAttribute('rel'));
})

it('should unset an attribute', function(){
var list = dom('<div><a href="/something"></a></div>').find('a');
list.attr({ href : null });
assert(null == list.get(0).getAttribute('href'));
})

})
})

describe('.prop()', function(){
Expand Down