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 used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Document Object - DOM

Last accessed pages

  1. Mysql SELECT JOIN tables on two different Databases (4498)
  2. jQuery UI draggable - Drag elements (11448)
  3. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (142520)
  4. Using the Bone Tool (4253)
  5. Node.js Move and Copy Directory (20134)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (523)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (62)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)