This last week I have been learning about accessing and manipulating the DOM using JavaScript. In order to help in processing the many commands there are, I decided to put together a DOM cheat sheet of all the basic commands I am most likely to use on a regular basis and I can refer back to.

  • In the DOM, all HTML elements are defined as objects.
  • A method is an action you can do (e.g. adding or removing HTML elements).
  • A property is a get or set value (e.g. changing HTML content)

Finding HTML Elements

Method:

document.getElementById (id)  – Find an element by element id
document.getElementsByTagName (name)  – Find elements by tag name
document.getElementsByClassName (name)  –  Find elements by class name
document.querySelector (css selectors) –  Find first element that matches a specific CSS selector
document.querySelectorAll (css selectors)  – Find all elements that match a specified CSS selector

Changing HTML Elements

Property:

element.innerHTML = new html content  –  Change the inner HTML of an element
element.attribute = new value –  Change the attribute value of an HTML element
element.style.property = new styleChange the style of an HTML element

Method:

element.setAttribute (attribute, value)Change the attribute value of an HTML element 

Adding and Deleting Elements

Method:

document.createElement (element)  – Create an HTML element
document.removeChild (element)  – Remove an HTML element
document.appendChild (element)  – Add an HTML element
document.replaceChild (new, old)  – Replace an HTML element
document.write (text)Write into the HTML output stream 

Adding Events Handlers:

Method:

document.getElementById(id).onclick = function(){code}Adding event handler code to an onclick event

Conclusion

So these are the commands that I have been finding most useful this last week. The DOM can get far more complex, but creating this cheat sheet has enabled me to remain focused and take action with manipulating the DOM with JavaScript. I will be sure to add to this on my blog as I develop my knowledge.