To access an element of a particular type the .getElementsByTagName(); method should be used.


var myElement = document.getElementsByTagName("p");  //returns an array of all found elements


If no element is found the returned array will be empty.


Specific returned elements can be accessed using square bracket array [ ] index notation (starting from 0).


e.g. if there were 7 <p> elements in the document, the 2nd could be accessed like so:





If a large number of elements were found it might make it tricky to home in on a specific target element and therefore a combination of .getElementById(); and .getElementsByTagName(); could be used together. e.g. say the .getElementsByTagName(); returned a large number of <p> elements and you only wanted to access those under a certain div, assuming the div had an id attribute, then a new variable could be assigned to that div and then the same .getElementsByTagName(); method can be applied to the new variable, like so:


var myParas = document.getElementsByTagName("p");  //gets all <p> elements

var myDiv = document.getElementById("theDivId") ; //assigns variable handle to target dive

var divParas = myDiv.getElementsByTagName("p"); //target div now has .getElementsByTagName(); method applied


Now, just the <p> elements within the target div are assigned to a variable based on the target div.


This example illustrates the above technique using JavaScript to display the <p> elements in the div with id="myDiv". I've also used css to set the display:none, and then let JavaScript display the found text:

Save & refresh browser:

Using JavaScript to extract just the text within the p tags of myDiv:
First line of text.
Second line of text.
Third line of text.




Just placing a few reminders here for the time being...

Node.nodeType //returns 1 for an element, 2 for an attribute, 3 for a text node
Node.innerHTML //returns text inside element tags
Node.childNodes //returns array of child nodes
Node.childNodes.length //returns length of array of childNodes

Leave a Reply