Javascript Course


The document object is created by the browser for each HTML page (document) that is viewed.
DOM stands for "Document Object Model", it is a hierarchical structure where each object can be accessed hierarchically starting from the first level, using a syntax: parent.child.
The document object contains the HTML elements of the page: tags, CSS properties, attributes and text, as you can see in the following image.
DOM document HTML tree


document object

document object represents the web page, it contains the elements (HTML tags), the attributes and the contents of a web page.
It contains properties and methods that can add, access, edit, delete HTML elements and content on the page.
The document object is a property of the window object, and can be accessed through the window.document, but, because the "window" is the main object, it can be omited, so the properties and methods of the document object can be accessed with this syntax.

document.property_name
document.methodName()
- For example: document.write('String') writes the specified 'String' in page.

A list with useful properties and methods of the document object can be found to:
coursesweb.net/javascript/properties-methods-document


Using properties of the document object

The document contains many properties to access the elements of the page. Most are read-only, but a few are also for writing.
Here are some examples.

document.URL - returns a string with the page address.
<script>
var url = document.URL;
document.write('URL:<br>'+ url);
</script>
document.title - returns or changes the page title (from the <title> tag).
<script>
var title = document.title;
document.write('Title:<br>'+ title);

//it changes the title
document.title ='Peace is good';
</script>

The properties can also contain objects that have their own properties and methods.

• For example: document.links - contains an array of objects with all the links (<a> tags) in page. They have properties specific to the HTML elements, which represent the component parts (attributes, text).
The following example displays the 'href' address of the links in page.
<a href='//marplo.net' title='MarPlo.net'>MarPlo.net</a>
<ul><li><a href='//gamv.eu' title='GamV.eu'>GamV.eu</a></li></ul>
<div><a href='//coursesweb.net' title='CoursesWeb.net'>CoursesWeb.net</a></div>
<hr>

<script>
var alnk = document.links; //array with all the links

//traverses the array and display the href value
for(var i=0; i<alnk.length; i++) document.write('<br>'+ alnk[i].href);
</script>

• The innerHTML property belongs to the HTML objects in document. It returns or sets the content of the HTML element to which it is applied.

- The following example takes the content from the first link on the page, then modifies it.
<a href='//marplo.net' title='MarPlo.net'>MarPlo.net</a>
<ul><li><a href='//gamv.eu' title='GamV.eu'>GamV.eu</a></li></ul>
<div><a href='//coursesweb.net' title='CoursesWeb.net'>CoursesWeb.net</a></div>

<script>
var alnk = document.links; //array with all the links

//gets the content of the 1st link
var txta1 = alnk[0].innerHTML;

//changes the content of the 1st link
alnk[0].innerHTML ='Text changed from JS';

//shows the initial text in console
console.log('The initial text of the first link: '+ txta1);
</script>

Using methods of the document object

The document object contains many methods for getting and changing HTML elements on the page in JS scripts.
Here are some examples.


document.getElementById('id') - returns the HTML element that has the specified id.

More details and examples with getElementById() can be found in the tutorial from: coursesweb.net/javascript/getelementbyid

Example, it reads the content of a Div and adds it with the textContent property in other HTML element.
<p id='prg1'>Example with <em>getElementById()</em></p>
The content from #prg1 is: <span id='sp1'>str</span>

<script>
//gets the html element with id prg1
var elm = document.getElementById('prg1');

//gets the html content from elm
var elm_cnt = elm.innerHTML;

//adds the string from elm_cnt as text in #sp1
document.getElementById('sp1').textContent = elm_cnt;
</script>
getElementsByTagName('tag') - returns an array of objects with the HTML elements that have the specified 'tag' name.

More details and examples with getElementsByTagName() can be found in the tutorial from: coursesweb.net/javascript/getelementsbytagname

Example, displays the number of H3 tags in page, and the id of the first H3.
<h3 id='id_elm'>Where two are, there is only one, two times.</h3>
<div>Div, HTML content</div>
<h3>Another H3 tag</h3>
<blockquote id='resp'>For response from JS.</blockquote>

<script>
//array with H3 tags
var ar_h3 = document.getElementsByTagName('h3');

//adds in #resp number of H3 and the id of first H3
if(ar_h3.length >0){
 var idh = ar_h3[0].id; //the id of first item in ar_h3
 document.getElementById('resp').innerHTML ='There are '+ ar_h3.length +' H3 tags, the first H3 has id: '+ idh;
}
</script>

Working with Properties and Methods of HTML elements in JS

In JavaScript, the HTML elements have properties and methods for accessing and manipulating their component parts (attributes, css styles, content).
They are applied directly to that HTML object.

elmHtml.property
elmHtml.method()
- 'elmHtml' is the HTML element returned by specific DOM methods in JavaScript (from document).

A list with useful properties and methods of the HTML objects can be found at:
coursesweb.net/javascript/properties-methods-html-elements

Examples

elmHtml.addEventListener('event', callback) - calls the function from callback when the specified 'event' is emitted (see the tutorial from: coursesweb.net/javascript/register-detect-event-handlers).
- Example, when you click on a specified button, it shows an alert() dialog box with content from a HTML tag.
<p id='prg1'>Ex. addEventListener(), click.</p>
<button id='btn1'>Click</button>

<script>
//when click on #btn1 it executes a function
document.getElementById('btn1').addEventListener('click', (ev)=>{
 var cnt = document.getElementById('prg1').textContent;
 alert(cnt);
});
</script>
elmHtml.parentNode - returns the parent element.
elmHtml.className - returns the value of the class attribute.
- Example, when you click on a specified button, it displays an alert dialog with the css class of its parent.
<div class='cls_1'>Div with a button: <button id='btn1'>Click</button></div>

<script>
//when click on #btn1 it executes a function (ev is an object with the event)
document.getElementById('btn1').addEventListener('click', (ev)=>{
 //gets the parent (ev.target is the element that triggered the event)
 var parent = ev.target.parentNode;

 //gets the class
 var cls = parent.className;

 alert('The parent element has class='+ cls);
});
</script>
elmHtml.setAttribute('attr', 'val') - sets the specified 'attr' attribute with the value 'val'.
elmHtml.outerHTML - returns a string with the whole HTML element (including its tag and content). Or replaces 'elm' with other HTML content..
- Example, when you click on a button, sets a 'style' attribute with css properties to an HTML element, then it removes the button.
<p id='prg1'>Peace, Joy, and Goodness Build Health.</p>
<button id='btn1'>Click</button>

<script>
//when click on #btn1 it executes a function (ev is an object with the event)
document.getElementById('btn1').addEventListener('click', (ev)=>{
 //sets style at #prg1
 document.getElementById('prg1').setAttribute('style', 'color:#0000e0; font-size:22px;');

 //removes the button (ev.target is the element that triggered the event)
 ev.target.outerHTML ='';
});
</script>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is a block element?
<div> <img> <span>
<div>Web Programming and Development</div>
Which CSS code displays the text underlined?
font-style: italic; text-decoration: underline; font-weight: 500;
h2 {
  text-decoration: underline;
}
Click on the JavaScript function that can access other function after a specified time.
insertBefore() setTimeout() querySelector()
function someFunction() { alert("CoursesWeb.net"); }
setTimeout("someFunction()", 2000);
Click on the instruction that returns the number of items of a multidimensional array in PHP.
count($array) count($array, 1) strlen()
$food =["fruits" =>["banana", "apple"), "veggie" =>["collard", "pea"));
$nr_food = count($food, 1);
echo $nr_food;       // 6
Document Object - DOM

Last accessed pages

  1. Remove / Get duplicate array values - Reset array keys in PHP (13046)
  2. Create simple Website with PHP (43835)
  3. Refresh page if window width changes from a device size to other (1732)
  4. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (55423)
  5. Clear Canvas Context (8002)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (324)
  2. Read Excel file data in PHP - PhpExcelReader (119)
  3. The Four Agreements (97)
  4. PHP Unzipper - Extract Zip, Rar Archives (94)
  5. The Mastery of Love (87)