Javascript Course


getElementsByTagName() is a method that returns an array filled with all the elements in the document that have the specified tag name sent as a argument.
Syntax:

document.getElementsByTagName('div')
- refers to all DIV tags.
This function stores the items into an array-object, where the keys are integers starting from 0.
If we wanna refer to the first <div>, we use:
var div1 = document.getElementsByTagName('div')[0];
- For the second <div>, we use index [1], and so on.

• You can use a wildcard symbol ( * ) to get a collection of all the tag elements in a specified HTML elements. For example, to get a list of all the HTML tags in a Div object, you can write:
var tab_tags = divOb.getElementsByTagName('*');

• To get the number of elements, you can use the length property:
var divs = document.getElementsByTagName('div');
var nr_divs = divs.length;

The array returned by getElementsByTagName() can be parsed with a for() instruction. To its items you can apply properties and methods specific to HTML objects in JavaScript.
See the list from the page: coursesweb.net/javascript/properties-methods-html-elements


Applying a property to elements with the same tag

To apply a property to the HTML elements that have the same tag, you have to traverse the Array returned by the getElementsByTagName() method. As a general syntax, it can be used the following code:
var elms = document.getElementsByTagName('tagName');
for (var i=0; i<elms.length; i++){
 elms[i].property;
}
- 'elms[i].property' apply the JS 'property' to all 'elms' (tag elements).

Here's an example. When a specified button is pressed, it sets a css style to every <span> tag:
<h4>Example getElementsByTagName</h4>
<p>Content with strings enclosed in SPAN tags:<br>
coursesweb.net : <span>Free</span> web JavaScript <span>Courses</span> and <span>tutorials</span>.
</p>
<p>- Click on the button to set CSS properties: 'color' and 'text-decoration' to all SPAN tags in page.</p>
<button id='btn1'>Style Span</button>

<script>
function adStyle(tag){
 //array with all the tags specified in 'tag' parameter
 var elms = document.getElementsByTagName(tag);

 //traverse the elms array
 for(var i=0; i<elms.length; i++){
 //apply style properties
 elms[i].style.color ='blue';
 elms[i].style.textDecoration ='underline';
 }
}

//when click on #btn1 it calls adStyle() with 'span' argument
document.getElementById('btn1').addEventListener('click', (ev)=>{
 adStyle('span');
});
</script>

getElementsByTagName() after getElementById()

When you use document.getElementsByTagName('tagName') it gets a reference to all 'tagName' in the HTML document. There are cases when you want to get only the tags within another tag. In this case, add an ID to that HTML element. In the JS script you can use getElementById() to get an object of that element, than, you can apply getElementsByTagName() to that object.
Syntax:
var variable = document.getElementById('id').getElementsByTagName('tagName');
- Here's an example with two different <ul> lists. When a button is pressed, a CSS style will be applied to the <li> tags from the second <ul>.
<h4>Example getElementsByTagName() after getElementBiId()</h4>
<ul id='ul1'>
 <li>ul1 - The next one comes.</li>
 <li>ul1 - I came for nothing.</li>
</ul>
<ul id='ul2'>
 <li>ul2 - I am the one who comes,</li>
 <li>ul2 - To me.</li>
</ul>
<p>- If you click the button, it apply the CSS properties: 'color' and 'text-decoration' to LI tags in element with id 'ul2'.</p>
<button id='btn1'>Style Li</button>

<script>
function adStyle(id, tag){
 //array with specified 'tag' in the elementul with id from 'id
 var elms = document.getElementById(id).getElementsByTagName(tag);

 //traverses the array elms
 for(var i=0; i<elms.length; i++){
 //aplica proprietati de stil
 elms[i].style.color ='blue';
 elms[i].style.textDecoration ='underline';
 }
}

//when click on #btn1 it calls the adStyle() with the arguments for id and tag
document.getElementById('btn1').addEventListener('click', (ev)=>{
 adStyle('ul2', 'li');
});
</script>

getAttribute() and getElementsByTagName()

There are cases when you want to apply JavaScript effects or properties only to some elements with the same attribute, from a group of same tags.
If you want to add a JS effect or property to HTML elements that have the same attribute (and the same tag), use the getAttribute('attr_name') method inside the for() instruction used to traverse the Array returned by getElementsByTagName().
Syntax:
var elms = document.getElementsByTagName('tag');
for(var i=0; i<elms.length; i++){
 if (elms[i].getAttribute('attr_name')=='val'){
 // JS code ...
 }
}
- val is the value of the attribute from 'attr_name' in the specified 'tag'.

To understand better, study the following example. It has three <span> tags in a paragraph, and clicking on a button, it will add a background color only to the SPAN tags with 'data-bgr' attribute with the same value.
<h4>Example getElementsByTagName() and getAttribute()</h4>
<p>Content with texts in SPAN tags:<br>
<span data-bgr='yellow'>Free</span> web development <span data-bgr='yellow'>course</span> and <span data-bgr='green'>tutorials</span>.</p>
<p>- If you click on the button, it sets a background color to the SPAN tags that have 'data-bgr' attribute with 'yellow' value.</p>
<button id='btn1'>Add Bgr</button>

<script>
function adBgr(tag){
 //array with span 'tag'
 var elms = document.getElementsByTagName(tag);

 //traverses the elms
 for(var i=0; i<elms.length; i++){
 //checks the data-bgr attribute
 if(elms[i].getAttribute('data-bgr') =='yellow'){
 elms[i].style.background ='yellow';
 }
 }
}

//when click on #btn1 calls adBgr() function
document.getElementById('btn1').addEventListener('click', (ev)=>{
 adBgr('span');
});
</script>

Registering events to HTML tags when the document is loaded

Adding JavaScript events (like onclick(), onmouseover(), ...) in a HTML tag, can make a function to be called when that event is triggered. But when you want to apply a JS event to multiple HTML elements, you have to add that event-attribute to each of them. This thing can aglomerate the HTML code, and it's better when you can separate the HTML and JavaScript code.
JavaScript can use the HTML elements that are already loaded, and can store events in memory without adding event-attribute in HTML tag.
To do that, you can add the script at the end of the HTML document (before the ending </body>), or use the DOMContentLoaded event to the document object.
- Syntax:
document.addEventListener('DOMContentLoaded', someFun);
- someFun is a function that will be called after the HTML elements are loaded in DOM.

Study the code of the following example. When the HTML is loaded in DOM, it gets in JS an <input> element and <li> tags, and registers 'click' event to these objects.
<h4>Example DOMContentLoaded</h4>
<p>- After the HTML document is loaded, it gets an Input element and the LI tags, and registers 'click' event to those objects.<br>
If you click on any of the lists below, it adds its text in the input field.</p>
Input Text: <input type='text' id='inp1' readonly/>
<ul>
<li>Peace is Good.</li>
<li>Forgiving brings happiness.</li>
<li>Love's Divine</li>
</ul>

<script>
var inp1; //it will contains the #inp1 element

//function called with DOMContentLoaded
function liClick(){
 inp1 = document.getElementById('inp1'); // #inp1 text field

 //array with LI tags
 var elms = document.getElementsByTagName('li');

 //traverses elms and registers click to each item
 for(var i=0; i<elms.length; i++){
 elms[i].addEventListener('click', (ev)=>{
 inp1.value = ev.target.textContent;
 });
 }
}

//after the HTML is loaded in DOM, calls liClick()
document.addEventListener('DOMContentLoaded', liClick);
</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
Working with getElementsByTagName

Last accessed pages

  1. Node.js Move and Copy file (28419)
  2. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (141747)
  3. Rectangle, Oval, Polygon - Star (3322)
  4. PHP PDO - prepare and execute (9187)
  5. jQuery Ajax - load() method (10835)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (471)
  2. CSS cursor property - Custom Cursors (78)
  3. The Mastery of Love (69)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (62)
  5. CSS3 2D transforms (46)