Projects

Creating Content with JavaScript

Update Existing Page Content

Three ways to get and set HTML content:

  • innerHTML
  • textContent
  • innerText

InnerHTML

Every element inherits properties and methods from the Element Interface. This means that every element has an .innerHTML property. This property represents the markup of the element's content.
This property can be used to:

  • get an element's (and all its descendants) HTML content
  • set an element's HTML content

The .innerHTML property sets or returns the HTML content inside the selected element (between the tags).

There's also the rarely used .outerHTML property. This represents the HTML element itself, as well as its children.

.innerHTML and .outerHTML property examples

textContent

.innerHTML will get/set an element's HTML content.
.textContent will get/set just the text content.

.textContent property will

  • set the text content of an element and all its descendants
  • return the text conent of an element and all its descendants

.innerHTML contains all the HTML for the element.
.textContent contains only the text of the element.

Setting/changing an element's text content:
example.textContent = "I will be the updated text for the example element."

Setting/changing an element's HTML content: example.innerHTML = "I <strong>WILL</strong> update the <strong>HTML</strong> for the <em>example</em> element"

.innerText

Like the .textContent property, the .innerText property can be used to get/set an element's text content, but there are some important differences;

  • .textContent - sets/gets the text content of an element
  • .innerText - sets/gets the text as it would be seen based on CSS

Update Existing Content

Multiple ways to change page contents:

  • .innerHTML
  • textContent
  • .innerText

To set HTML content for an element, we can only use .innerHTML. Using .textContent will include the HTML as plain text inside the element.

Also identified the difference between .textContent and .innerText. .textContent returns all the element's HTML text regardless of how CSS might hide. .innerText only returns what is displayed on the page by taking CSS into consideration.

Add New Page Content

  • .createElement()
  • .appendChild()
  • .createTextNode()
  • .insertAdjacentHTML()

.createElement()

.createElement() is a method used on the document

createElement() example

.appendChild()

.createElement only makes the element, but does not add it to the DOM. .appendChild method will add the created element to the page. To use the .appendChild method, it needs to be called on by another element, not the document object.

appendChild() example

The appendChild() method is called on one element, and passed to the element to append to. The element that is about to be appended is added as the last child. In the example avoce, the <span> element will appear in the DOM as a child of the <h1>; but will appear at the end, after all text and any other elements that might be in the <h1>.

.appendChild() NEEDS an element. It must be called on an existing element. Calling the method on the document object without an element, will produce an error.


.createTextNode()

.createTextNode() is similar to .createElement(); Except instead of an element, it creates new text nodes.

Because it is similar to .textContent property, it is often faster to use that property instead of the .createTextNode() method.

Link: MDN | createTextNode() method


.insertAdjacentHTML()

.appendChild() method will add an element as the last child of the parent element. It's impossible to put it as the first child or anywhere else; it has to be the last child.

.insertAdjacentHTML() method allows us to decide where to put the element in the parent element. It has to be called with two arguments:

  • position - the location of the HTML:
    • beforebegin - inserts the HTML text as the previous sibling
    • afterbegin - inserts the HTML text as the first child
    • beforeend - inserts the HTML text as the last child
    • afterend - inserts the HTML text as a following sibling
  • text - the HTML text that is going to be inserted

Note: The text has to be regular text. Typing HTML will display the HTML on the page as text.

.insertAdjacentHTML() method example

Methods for createing DOM elements and adding them to the page:

  • .createElement() - create new elements
  • .appendChild() - add a child element to a parent element as its last child
  • .createTextNode() - create a text node
  • .insertAdjacentHTML() - put HTML text anywhere around an element

Important notes:

  • If an element already exists in the DOM and this element is passed to .appendChild(), the .appendChild() method will move it rather than duplicating it
  • An element's .textContent property is used more often than creating a text node with .createTextNode() method
  • The .insertAdjacentHTML() method's second argument has to be text; you can't pass an element

Remove Page Content

Two methods to remove content from the page:

  • .removeChild()
  • .remove()

Two properites:

  • .firstElementChild
  • .parentElement

Removing a Child Element

Using .removeChild() method removes a child element. This is essentially the opposite of the .appendChild() method. requirements for .removeChild() method:

  • A parent element
  • The child element that will be removed

<parent-element>.removeChild(<child-to-removed>);

Like the .appendChild() method, .removeChild() also requires access to the parent to function.

Every element has a parentElement property that refers to its parent. If we have access to the child element, we can use the parentElement property to "move focus" to the element's parent. Then the methods .removeChild() or .appendChild() may be called on the referenced parent element.

.removeChild() method example

const mainHeading = document.querySelector('h1');

The code will select the first <h1> on the page and stores it in the mainHeading variable.

const mainHeading = document.querySelector('h1');

This starts with the mainHeading variable. calls .parentElement so the focus of the next code is directed at the parent element. Then .removeChild() is called on the parent element. Finally, mainHeading itself is passed as the element that needs to be removed from its parent.
Essentially, an element uses itself to remove itself from its parent.

We could simplify this if we're just going to remove the entire element with the .remote() method.

.remove() method example

Two methods to remove an element from the page:

  • .removeChild()
  • .remove()

.removeChild must be called on the parent of the element being removed and must be passed the child to be removed. .remove() can be called directly on the element to delete.

Properties to use when removing content:

  • .firstChild
  • .firstElementChild
  • .parentElement

.firstElementChild wil always return the first element. .firstChild might return whitespace (if any) to preserve the formatting of the HTML source code.

Style Page Content

We can control the page and element styling using the following properties and methods:

  • .style.<property>
  • .cssText
  • .setAttribute()
  • .className
  • .classList

To access an element's style attribute, use the .style property.


    const example = document.querySelector('h1');   
    example.style.color = 'red';                    

Using .style property, only ONE CSS style can be modified at a time.

Access Multiple Styles with cssText

.style.cssText property allows writing CSS styles similar to using a stylesheet. While using .cssText, the styles will be writen just like writing CSS.


    const example = document.querySelector('.class');                               
    example.style.cssText = 'width: 30px; text-decoration: underline; color: red';  

Setting styles with setAttribute

.setAttribute() method is similar to the .style.cssText property; It allows you to set multiple styles for an element.


    const example = documnet.querySelector('#idName');                                          
    example.setAttribute('style', 'color: orange; background-color: black; font-size: 20px;');  

.setAttribute() is not just for styling page elements. This method may be used to set any attribute for an element; such as giving an element an ID.


    const exampleHeading = document.querySelector('h1');                        
    //add an ID to the heading's sibling element                               
    exampleHeading.nextElementSibling.setAttribute('id', 'example-sibling');    
    //use the newly added ID to access that element                            
    document.querySelector('#example-sibling').style.backgroundColor = 'red';   

Setting Styles and Seperation of Concerns

  • HTML should be in a .htm document
  • CSS should be in a .css document
  • Interactivity (JavaScript) should be in a .js document

Keep all the styles in CSS. Control class attributes for an element with JavaScript code. This allows change to styling by adding or removing classes.

.className property returns a space-seperated string of all element's classes.
const listOfClasses = example.className;
console.log(listOfClasses);

Because .className is a property, it can be set its value just by assigning a string to the property.
example.className = 'new-class';
This erases any existing classes in the element's class attribute and replaces it with the single class new-class.

To add or remove an individual class, the .className space-seperated string into an array using .split()
const arrayOfClasses = listOfClasses.split(' ');
With an array of classes, we can do data-intesive calculations:

  • use a for loop to loop through the list of class names
  • use .push() to add an item to the list
  • use .splice() to remove an item from the list
  • use .join() to convert the array back into a string

The .classList property is newer than .className.
MDN | classList Property

.classList property has many methods of its own. Some of the popular ones are:

  • .add() - add a class to the list
  • .remove() - removes a class from the list
  • .toggle() - add the class if it doesn't exists or removes it if it does exist
  • .contains() - returns boolean based on if the class exists in the list or not