about the DOM¶
the DOM is the tree of the HTML code, as already seen
the DOM can be read and modified in JavaScript, using the global variable
documentthe DOM exposes a standard API, see the details on Mozila MDN
spotting elements in the DOM¶
get element by their id:
document.getElementById("some-id")get all elements matching a selector
document.querySelectorAll(".the-class")
this kind of functions also work from a given element, for exemple:// spot one specific element in the tree const root = document.getElementById("some-id") // find all elements under 'root' with class 'the-class' root.querySelectorAll(".the-class")
messing with an element¶
classes¶
manage the class(es) of an element
element.classList// add a class element.classList.add("another-class") // remove a class element.classList.remove("another-class") // remove or add element.classList.toggle("some-class")
properties¶
to read a computed property (the one actually applied), you’d do
// e.g to read the 'background-color' property window.getComputedStyle(element).backgroundColorand to set an element property:
several angles are possible, here we are writing directly in thestyle=part of the element
and so, in line with the specificity rules, this will win over all other applicable settingselement.style.backgroundColor = "rgb(10, 23, 255)"
attributes¶
read the attribute of an element
element.getAttribute("someattr")
write it withelement.setAttribute("someattr", somevalue)
what’s an attribute again ?
to set this attribute in HTML, one would have written <div someattr="some-value">...</div>
not to be confused with properties !
creating DOM element from scratch¶
simply use e.g.
document.createElement("div")mind you, sometimes - like for svg elements for example -
you need to specify a namespace withcreateElementNS()
see the cheatsheet below for an examplein any case, don’t forget to add the new element somewhere in the tree
father.appendChild(new_node)
because otherwise it won’t appear in the page at all !
summary / cheatsheet¶
click on ‘Open in new window’ to see a cheatsheet that contains all this
other ways to access the cheatsheet
if you have cloned the course repo: open
notebooks/_static/cheatsheet.htmlalso there used to be a bookmarkable link - but it might be broken now
practice: a dynamic grid - step 1¶
now could be a right time to start the dynamic grid exercise on github !
start with just Step 1:
write a function that adds a line,
and see the initial examples on how to attach that function to the button