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 HTML element can be used to embed a SWF flash content?
<object> <div> <script>
<object type="application/x-shockwave-flash" data="file.swf" width="500" height="250">
 <param name="src" value="file.swf" />
 Your browser not support SWF.
</object>
Which CSS pseudo-class adds a style to an input form field that has keyboard input focus?
:active :focus :hover
input:focus {
  background-color: #88fe88;
}
Click on the instruction which converts a JSON string into a JavaScript object.
JSON.stringify(javascript_object) object.toString() JSON.parse(json_string)
var jsnstr = '{"url": "http://coursesweb.net/", "title": "Web Development Courses"}';
var obj = JSON.parse(jsnstr);
alert(obj.url);
Indicate the PHP function which can be used to create or write a file on server.
fopen() file_put_contents() file_get_contents()
if (file_put_contents("file.txt", "content")) echo "The file was created";
else echo "The file can not be created";
Working with getElementsByTagName

Last accessed pages

  1. Simple Admin Login PHP Script (1208)
  2. Follow the mouse cursor with a DIV inside a Parent (2915)
  3. JavaScript code and PHP (21587)
  4. Add Pause in JavaScript script (9991)
  5. Input text fields (2286)

Popular pages this month

  1. Insert, Select and Update NULL value in MySQL (558)
  2. Read Excel file data in PHP - PhpExcelReader (467)
  3. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (342)
  4. PHP getElementById and getElementsByTagName (266)
  5. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (253)