Simplest DOM
A simple DOM implementation that can be used on server-side for rendering and tests purpose.
This project was created when I decided to cover react-vanilla with server side tests. There are some heavy existed packages, but I want something lightweight that would not bloat my node_modules.
- addEventListener(eventName, callback) — subscribe to some event
- appendChild(child) — add child element
- createElement(tagName) — return a dom element
- createTextNode(text) — create text node dom element
- emit(eventName) — fire an event (it is not emulated DOM event, just observable triggering)
- getAttribute(attributeName) — get attribute of an element
- getElementById(id) — get element by id
- getElementsByClassName(className) — get elements by class name
- getElementsByTagName(tagName) — get elements by tag name
- insertBefore(newChild, refChild) — insert element before another
- querySelector(selector) — only simple selectors are supported. return single element
- querySelectorAll(selector) — only simple selectors are supported. return an array of elements
- removeAttribute(attributeName) — remove attribute from DOM element
- removeChild(child) — remove child from parent
- removeEventListener(eventName, callback) — unsubscribe from event
- setAttribute(attributeName, value) — set elemnt's attribute
Supports innerHTML\outerHTML properties getters.
Was tested on parsing huge legacy html pages, updating some elements and getting new HTML. (Production code)
Install
npm install simplest-dom
Usage example:
import Dom from 'simplest-dom';
global.document = new Dom();
global.DocumentFragment = document.DocumentFragment;
// test cases would think that document exists
// .........
Parsing some site and adding outer links rels:
var doc = new Dom( html );
var allPageLinks = [...document.querySelectorAll('a')];
// MODIFY EXTERNAL LINKS
allPageLinks.filter(a=>{
var href = a.getAttribute('href');
if(!href)
return false;
if(href.indexOf('http')!==0)
return false;
if(href.indexOf('myDomain.com')>0)
return false;
return true;
})
.forEach(item=>
item.setAttribute('rel', 'nofollow noopener noreferrer', 1)
);
console.log(doc.outerHTML);
Code is covered with tests.