Today, I want to discuss interacting with your HTML content. Many times in JavaScript programming, we wish to interact/affect our HTML content in some fashion. We may want to add, remove or change content. So how do we go about doing that? TO accomplish this, we need to set up our HTML correctly and then code our JavaScript for our HTML. Let’s look at how we might do that…
In HTML, we need to ensure we set up our structure of our content appropriately. One aspect of this is utilizing the ID attribute. WHen I build web apps, I usually ID and class (which we will talk about in a future post) a ton of stuff. This allows me to utilize not only proper JavaScript coding, but also CSS to make  my apps ‘prettified’. So what does this ID attribute look like?
[code lang=”html”]
<div id="myDiv">
Some content…
</div>
[/code]
As you can see, I have an ID attribute on my div entitled, ‘myDiv’. We can put IDs on virtually any HTML tag. The only real rule is that each ID needs to be unique on a page. In other words, I cannot have two ‘myDiv’ IDs on the same HTML page.
So how does this work with JavaScript? We, we can grab that tag element by the ID and do what we want with it. We do this by using the getElementById() method. Here’s an example…
[code lang=”js”]
// Create variable to hold myDiv div
var myVar;
// Grab myDiv and put it into myVar
myVar = document.getElementById("myDiv");
[/code]
What the above code does is grab the myDiv div and stick it into the myVar variable. Another way of reading line four (4) is to say, “Go into my document, get the element with the ID of myDiv.” All we need to do is pass the ID we want to grab to the getElementById() method. So what good does this do us? Now that we have it sitting in a variable, we can manipulate the content using that variable as a vehicle. As I stated earlier, we can add/change/delete content. In JavaScript coding, you will find that you will use this method very often.
Happy Coding!
Clay Hess