The below code shows the body of a html document with three element. First there is a paragraph element, then a div element with the id of ‘myDiv’ and finally a span with the class name ‘mySpan’. Remember, within a html document an id must be unique and classnames don’t have to be unique. This means that many elements can share the same classname but only one element can have a unique id. This means that every element can have their own id, but they all must be unique.
<body> <p></p> <div id="myDiv"></div> <span class="mySpan"></span> </body>
var p = document.getElementsByTagName("p"); p.innerText = "<i>Hello World</i>";
The next way we can access elements is by getting it by the id. Id’s must be unique, so this will only return one element. The ‘innerHTML’ field is used to set html inside the element. The html in the value will be rendered, so the ‘strong’ tag will be rendered as the ‘innerHTML’ is used rather than the ‘innerText’. This means the ‘Hello World’ will be displayed in the div as it will be bold, as the ‘strong’ tag makes text bold.
var div = document.getElementById("myDiv"); div.innerHTML = "<strong>Hello World</strong>";
The final way to grab elements from a html document is to get it by the classname. This will also return a array, as multiple elements can share classnames. The innerText is also used, which means any html will not be rendered and will be displayed as normal text.
var span = document.getElementsByClassName("span"); span.innerText = "This is my span";
The three functions used to grab elements in html document can be used to get elements by the tagname, the id, or the classname. Dependent on which function used either a single element will be returned or a list of elements will be returned. The ‘innerHTML’ method can be used to render html within elements, such as make text bold. The ‘innerText’ method can also be used to set text of an element but will not render html tags, so it will be show the text value of tags instead of the rendered html.