JavaScript DOM Notes


Select DOM element

  • Use var elem = document.getElementById( "id" ); to get an element by it's ID attribute.
  • Use var elemArray = document.getElementsByClassName( "class" ); to get an array of elements with this class name.
  • Use var elemArray = document.querySelector( "selector" ); to get an array of elements that have this CSS selector.

Create HTML element

  1. Use var elemNode = document.createElement( "tag" ); to create the base element.
  2. Use var node = document.createTextNode( "string" ); to create the text that would be inside an HTML tag.
  3. Use elemNode.appendChild( node ); to add the text to the HTML element
  4. Use var element = document.getElementById( "main" ); to grab the main HTML element.
  5. Use element.appendChild( elemNode ); to add the constructed element to the main HTML tag.

Change attributes of HTML element

  • Use var elem = document.getElementById( "id" ); or some such to grab an element.
  • Use elem.setAttribute( attr-name, attr-value ); to set the attribute on that element.
  • For example:
    img.setAttribute( "src", "img.picture.jpg" );
    img.setAttribute( "width", "450" );
  • Use elem.classList.add( "class1", "class2", "class3" ); to add classes to the HTML element.