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
- Use
var elemNode = document.createElement( "tag" ); to create the base element.
- Use
var node = document.createTextNode( "string" ); to create the text that would be inside an HTML tag.
- Use
elemNode.appendChild( node ); to add the text to the HTML element
- Use
var element = document.getElementById( "main" ); to grab the main HTML element.
- 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.