More often than not, you do not program in a vacuum. That is true not only of the process and a team of people but with code itself. What I mean is that you typically do not simply build JavaScript (or some other code language) applications by themselves, but, rather, JavaScript interacts with HTML and CSS. HTML pages (or our content) are documents of text that are structured into pieces. When someone creates an HTML page, they create a hierarchical structure…head, body, header, section, nav, footer and more. The functionality of a web app is provided by JavaScript (typically). So, in order to have high quality, interactive, robust applications, JavaScript has to be able to work within and manipulate the HTML document. This is done utilizing what is known as the Document Object Model (DOM). JavaScript has built in functions/methods that allow a developer to pretty much do whatever they would like with an HTML document. Today I want to show one example…grabbing an element or tag by their ID.
Whenever I create an HTML document, I utilize the ID and class elements extensively. This is key for styling a page and for the interactivity. Let me show you how you can use the ID of an element to manipulate the DOM. First, let’s talk about IDs. The syntax for an ID is as follows…
[code lang=”js”]
<!– A typical HTML tag..in this case a form input tag. –>
<input type = "text" id = "someID" name = "someName">
<!– This code would result in a form text box being output to the HTML document. –>
[/code]
Notice that I have the ID attribute with the value of “someID”. One thing to note about IDs is that they can only exist one time within any HTML document. What that means is that there can only be one element with the ID of “someID”. I cannot create another element and re-use that same ID. This is to our advantage, because we can use JavaScript to grab that element, in this case, the input tag.
So how do we do that? We use a function/method entitled, “getElementById()”. Here is an example…
[code lang=”js”]
// Create a variable to hold the information from our input tag element
var myVar;
// Grab the value of the input tag field and store it in myVar
myVar = document.getElementById("someID").value;
[/code]
So the way this works is we tell the JavaScript interpreter to go into the document, get an element by the ID of someID and then grab the value of that element. Since this is a form field, what that means is we can grab whatever information the end user typed into the form text field. We can take that information and store it in a variable like I have done here and then do with it what we would like. FYI, in this case I am grabbing the element’s value, but you do not have to do that. You can simply grab the entire element without the “.value” on the end.
Happy Coding!
Clay Hess