Skip to content

Commit

Permalink
add support for modifying existing elements
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel-Hug committed Jan 23, 2016
1 parent 302db83 commit 76a9b86
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
18 changes: 17 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Generate views from JS easy peasy with `dom()`. See demos:
- [counter](http://jsbin.com/riyiwo/edit?js,output)
- [search form](http://jsbin.com/qisopo/edit?js,output)

### Create an element
### Create or modify an element
**pass:** [node value](#node-values)
**returns:** DOM node

Expand Down Expand Up @@ -43,6 +43,22 @@ document.querySelector('.shopping-list').appendChild(docFrag);
```


### Modify existing elements
All the properties we are using in our plain object node values to render new elements can also be used to modify existing elements. This includes adding kids, event listeners, or classes; setting HTML attributes or an element's text; and setting JS properties.
Let's modify the above example to stick our list items in an existing list using DOM Builder:

```js
var docFrag = dom({
el: document.querySelector('.shopping-list'),
kids: [
{ el: 'li', text: 'Milk' },
{ el: 'li', text: 'Butter' },
{ el: 'li', text: 'Juice' }
]
});
```


### Add child elements
Set the `kids` property to an array of [node values](#node-values)

Expand Down
3 changes: 2 additions & 1 deletion dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@
}

function createEl(elData) {
var el = document.createElement(elData.el || 'div');
var el = elData.el instanceof HTMLElement ? elData.el :
document.createElement(elData.el || 'div');

Object.keys(elData).forEach(function(key) {
if (['el', 'text', 'kids'].indexOf(key) === -1) {
Expand Down
9 changes: 6 additions & 3 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
});

// <button>0</button>
var button = dom([
var buttonModule = dom([
{
el: 'button',
text: counter.snoop('count'),
Expand All @@ -70,8 +70,11 @@
}
]);

// append to <body>
document.body.appendChild(button);
// equivalent to: document.body.appendChild(buttonModule);
dom({
el: document.body,
kids: [buttonModule]
});
</script>
</body>
</html>

0 comments on commit 76a9b86

Please sign in to comment.