Html DOM

From wikinotes
Revision as of 15:22, 18 December 2022 by Will (talk | contribs) (→‎Examples)

Query/Manipulate an HTML page from javascript using it's DOM (domain-object-model).

Documentation

DOM docs https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model

Examples

You can select items from javascript using css selectors.

document.querySelector('div.foo-class');      // find first matching item by CSS-selector
document.querySelectorAll('div.foo-class');   // find all matching items by CSS-selector
document.getElementById('foo-id');            // find element with ID
document.getElementsByClassName('foo-class'); // find elements with class

// find all 'li' children of 'foo-id'
var foo = document.getElementById("foo-id");
foo.querySelectorAll("li");