Now that we know how to grab an HTML tag, let’s talk about manipulating the data inside. Manipulating elements is fairly easy.
So, let’s first clear out our script. Then, add this bit of code.
var p = document.getElementsByTagName( 'p' );
Just like last time, we store the tags inside a variable. Since there are 3 paragraph tags inside the HTML document, there has to be a way to grab a specific one. In our case, we use square bracket notation . You type these after our variable and inside these square brackets, you type in a number.
The number represents the order of the tags. In the programming world, everything starts with 0. So the the first paragraph tag is considered number 0. The next one is 1 and the last tag is 2.
Next, you access the innerHTML property and you can change the HTML inside this tag simply by assigning a new value. You can type html or just regular text. If you refresh the page, you should see the first paragraph be changed to this.
Let’s talk about how to get tags by their IDs. Clear your script and add this bit of code.
var p = document.getElementById( 'foo' );
We’re now using the method getElementById(). This method grabs an element with the name of the ID passed into it’s parameters. In our case, we wanted to grab any tags with the ID foo. In HTML, each ID name must be unique.
Since it has to be unique, we don’t have to specify which exact tag since there’s only one to begin with. After that, we change the HTML like last time. Refresh your page and you should see the same message as before except it should change the 2nd paragraph tag.
Let’s try grabbing classes now. Clear your script and add this bit of code.
var p = document.getElementsByClassName( 'foo' );
To grab a tag by it’s class, you use the getElementsByClassName() method. You pass in the class name. Unlike IDs, multiple elements can have the same class. So, even though there’s only 1 tag with the foo class. You still have to specify which one you want using square bracket notation.
Refresh your page and you should see the same message as before, but on the 3rd <p> tag.