Home

Document Object Model (DOM)

See an explanation on the W3Schools Website

See a comprehensive list of all document properties... MDN Document

(document.getElement(s)By....)

The DOM is a standard for how to get, change, add or delete HTML elements.

document.getElementsById()
The getElementById() method returns the element that has the ID attribute with the specified value.
And if you want to store an element as a variable do this, eg...
var myElement = document.getElementById("myId");


document.getElementsByClassName()
The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as an HTMLCollection object.

document.getElementsByTagName()
The getElementsByTagName() method returns a collection of all elements in the document with the specified tag name, as an HTMLCollection object.

document.getElementsByName()
The getElementsByName() method returns a collection of all elements in the document with the specified name (the value of the name attribute), as an HTMLCollection object.

NOTE
If you want to save the <body> then you could use
var myElement = document.body;
instead of 'var myElement = document.getElementByTagName("body");'
And make sure that your webpage has finished loading as 'getElementByTagName() (or any of the others) will not have a 'tag' to read yet....For this you would need to put the getElementByTagName in to a <script> which goes at the end of the web page.

document.getElementById

For example, if you had an element with the id="myElement1"...
<h3 id="myElement1">This is my test</h3>

Then you could say...
var aDom = document.getElementById("myElement1")

and aDom would then be what you could use to manipulate the element...eg...
aDom.innerHTML = "This WAS my test"
would change the original text (This is my test) to read This WAS my test

This is my test

document.getElementsByClassName

For example, if you had an element with the class="myElement2"...
<h3 class="myElement2">I am a class test</h3>

Then you could say...
var aDomC = document.getElementsByClassName("myElement2")

and aDomC would then be a collection that you could use to manipulate the element(s)...eg...
aDomC.innerHTML[0] = "Testing Classes"
would change the original text for the first element found in the collection - or you could read through the whole collection and change them all.

Note... testing this will also change the [H3] in the ID test as I also gave that a class of myElement2

ALSO...You can only search for one iteration at a time...so you have to perform multiple getElementByClassNames for more than one Class.
However if your element uses multiple classes (eg class="class1 class2") you can do a getElementByClassName("class1 class2") to find it.

I am a class test

Top

document.getElementByTagName

This time I shall grab ALL the [H3]'s and perform a FOR loop to show the details of each one found.
You can only search for one iteration at a time...so you have to perform multiple getElementByTagNames for more than one Tag.
document.getElementByTagName("h3")
Note...I used FOR/IN loop with getElementsByClassName okay BUT here it went wrong so I changed it to a FOR loop (for (i=0;...etc))


document.getElementByName

This time I shall grab ALL the elements that have a NAME and perform a FOR loop to show the details of each one found.
You can only search for one iteration at a time...so you have to perform multiple getElementByNames for more than one name.

eg...
<h4 name="myH4">This is a NAMED h4</h4> document.getElementByName("myH4")
Note...I used a FOR loop (for (i=0;...etc)) to read thru the returned collection

This is a NAMED h4 tag


Top

Some useful properties maybe

You will find it useful to look at w3schools site for more information on the properties that you can use with the getElement(s)By.... commands.

A few are listed here :-
.addEventListener() : Attaches an event handler to the specified element
.appendChild and .insertBefore : Used to create new elements (along with the .createElement method - see below examples
.attributes : Returns a NamedNodeMap of an element's attributes
.blur() : Removes focus from an element (see also focus())
.focus() : Gives focus to an element (see also blur())
.childElementCount : Returns a collection of an element's child nodes (including text and comment nodes)
.childNodes : Returns a collection of an element's child element (excluding text and comment nodes)
.children : Attaches an event handler to the specified element
.innerHTML : Sets or returns the content of an element
.offsetHeight : Returns the height of an element, including padding, border and scrollbar
.offsetLeft : Returns the horizontal offset position of an element
.outerHTML : Sets or returns the content of an element (including the start tag and the end tag)
.querySelector() : Returns the first child element that matches a specified CSS selector(s) of an element
.querySelectorAll() : Returns all child elements that matches a specified CSS selector(s) of an element

Some MORE useful properties maybe

You will find it useful to look at w3schools site for more information on the properties that you can use with the getElement(s)By.... commands.

A few more are listed here :-
.remove() : Removes the element from the DOM
.removeChild() : This method removes a specified child node of the specified element.
.removeAttribute() : Removes a specified attribute from an element
.removeEventListener() : Removes an event handler that has been attached with the addEventListener() method
.scrollHeight : Returns the entire height of an element, including padding
.scrollIntoView() : Scrolls the specified element into the visible area of the browser window
.getAttribute() : Returns the specified attribute value of an element node
.setAttribute() : Sets or changes the specified attribute, to the specified value
.style : Sets or returns the value of the style attribute of an element.
Note...in CSS it is background-colour and here it is style.backgroundColor so the '-' is missing and it uses camel case. (font-family vs style.fontFamily...etc)
.tabIndex : Sets or returns the value of the tabindex attribute of an element
.tagName : Returns the tag name of an element

Top

document.createElement()

Adding New Elements

To add a new element (assume <p>My New Text</p>) to your page you need to...

Create the element to be added
var newP = document.createElement("p")
Create a Text Node of text to be added
var txt = document.createText Node("My New Text");
Append the text to the new element
newP.appendChild(txt);
Find the element that you want to add the new code after
var foundElement = document.getElementById("myElem");
Append the new code to the old element you just found
foundElement.appendChild(newP);
Note...you only need to add newP as this now holds the <p> and the "My New Text" element.

************************

You can add new list items to an Unordered List, first you need to decide where to put it then you can add it, for example, lets say you have an unordered list with an ID of "myUList"
to add a new item to this unordered list :-

var myElement = document.getElementById("myUlist");
var newElement = document.createElement("li");

The above will create the new list item but next you would have to set all the attributes/properties for it.

The next step is to create a new text node and attach it to the element
var myText = document.createTextNode("My added Item");
newElement.appendChild(myText);


Then you need to append the newly created list item to the unordered list
myElement.appendChild(newElement);

This will add the new list item to the END of the unordered list... ALSO see below for another (working) example where you click a button to add

You can insert it into a specific spot in the Unordered List but that takes a bit of mucking about. I found that it was best to ask the position you want to add it then
Count the No. of LI's (to add at position 2 count 3 LI's) and then perform an .insertBefore() command.
I have got an example (see right pane) but it is best to look at the code to see how it works.

See .remove or .removeChild to remove elements.

For Example...

For example...to ADD a new <p>some new text</p> below this line


********************

For example,
My Unordered list is...

Now to add another line


Now to INSERT another line at position 2 (item count 1 as it starts at 0)
uses .insertBefore(..., ...)

Position:

Now to Show a list of NODES in the Unordered List as I need to know for INSERTING the line above
On the "li" items in the list this will show #text between each "li" BUT for lines added by clicking the buttons it does NOT show #text in between these lines.

Top

Only want to change the FIRST Element

If you have, for example, lots of <h1> tags but you only want to change the FIRST one...you could...give it an id name and then use that to identify it
OR you could use the document.querySelector() which returns the FIRST element it finds, eg...

document.querySelector("h1").innerHTML="This is my new value"

The above will change the value of the FIRST <h1> it finds to 'This is my new value'.

document.querySelector(".myClass").innerHTML="This is my new value"

The above will change the value of the FIRST element it finds that has a class called 'myClass' to 'This is my new value'.

For more on .querySelector() then click on the link in the list of useful properties above.

Example of creating a new element and appending it to another Element

In this example :-


let newDestination = document.createElement("li");
newDestination.id = 'addedOn';
newDestination.innerHTML='Here I am';
newDestination.style.color="red";
document.getElementById("myList").appendChild(newDestination);




(When the new line appears you can click the button again to make it disappear)
Top

Adding a new option to a <select> element

Usually you have something like...
<select id="bookList" size="1" name="bookList" onchange="bookSelected(this.value)">
   <option value="0">Pizza</option>
   <option value="1">Cheeseburger</option>
   etc...
</select>


I created a function to do this, pass in parameters where...
value = the value for the <option> section, eg '0'
text = the value that gets displayed, eg 'Pizza'

function addToBookList(value, text) {

   
//create a new 'option' to add to the <select> element
   let opt = document.createElement("option");

   opt.value = value;
   opt.text = text;
   
//Default is false but I wanted to show how to do this
   opt.selected = false;

   
//If you are building options from scratch you may want the first option to be set as selected, so...
(Note...this only works if 'value' is 0 for the first item)

   if (value == 0) {
      opt.setAttribute("selected", "");
      opt.selected = true;
   }

   
//Add the new 'option' to the 'select'
   document.getElementById("bookList")
         .options.add(opt);
   document.getElementById("bookList")

   
//'size=n' sets the number of lines to show in the 'select' element - and this will only work if value is actually a count of how many line items there are.
         .size = value + 1;
}

I actually use this scenario in the Books And Stuff web page.



Top