Getting and Setting DOM Elements:
At the beginning of this site, we used some code to color certain element of our HTML. Let's talk about these in more detail:
getElementById
:getElementsByClassName
:getElementsByTagName
getElementsByName
By far the most used. It targets element ids. In the HTML, we often set id="example"
. From JavaScript
,
we target these ids by their name.
But how does the code know where to look for these elements?
We use document
, for example. Thus:
Beneath this text is a blank <p> element with an Id set to "example". Because it is empty, nothing is showing in the browser. However, when we target that element with this button:
where onclick="example()"
tells the code which function ti run, then clicking the button will result in that function running, and
as if by magic, the word "Hi"
will appear underneath the button:
We also used the same method to color the text, using .style.color = "c13e70";
(There is a better way to style elements in JavaScript, we'll come onto that.
Operates much the same as the above, with a few differeces. It would be very rare to have an empty HTML document, in which we want to run the same text for every example of that class name. Getting element by their class name is mor about retrieving information from them. But, when you are looking for the class that contains for example the word "Hi", it would be like searching for a needle in a haystack. Thus, to retrieve that information, it is best to loop through it:
Note that all entries here are logged to the console. While when we try to display them in the browser, the last entry is displayed:
So, just like in a loop, to get the innerText
of a specific class, we select the entry using its [#]
:
Searches for all entries with a specific HTML tag name. The tag is CAPITALISED. Thus:
As there are many elements with the same tag on an HTML page, the same is true here for the above: loop through it.
Returns all elements with that name. Useful for input fields, for example:
Enter your name:
In the section on storage we learned that we had to assign key
/
value
to Objects in order to retrieve their values
. Let's do that now. Click the
"Click Me" button to see the code and result:
The difference between getting and setting elements in the DOM is that when we get the element we use this code:
whereas, when we set the element we assign it a value:
There are of course many other Methods for the DOM. You can find them here.