mercredi 29 août 2012
DOM: the document.getElement[s]By
Do you like this story?
I can feel that the summer is almost over and it's time to get to serious things again.
In the following post, we are going to see how to manipulate the DOM elements with document.getElement[s]By.
As you may know we have different way of manipulating DOM elements and here we will see all of them:
1) document.getElementById;
2) document.getElementsByClassName;
3) document.getElementsByName;
4) document.getElementsByTagName;
As you can see there are 4 possible way of using the document.getElement[s]By[something].
Are you ready?
General considerations
The above DOM functions work almost the same way: they consider DOM elements that have a specific argument like an ID or Name.
Said that it is easy to understand why it is better not to confuse them and possibly use mainly just one of them in our projects. As an example, if we use document.getElementById, we are going to consider all DOM elements which have a specific ID. That means we need to be sure to use IDs properly (for example just for one element if we don't want to manipulate more than one element).
Oh! Another thing: remember to be careful with the form of the code. For example document.getElementById has some capital letters ("E", "B" and "I"): we must respect that even if it looks strange!
Place the following function in the head of your document:
<script> function changeColor(newColor) {
var elemId = document.getElementById("div1");
elemId.style.color = newColor;
}
</script>
In the body of the document <div id="div1">Text example</div>
<button onclick="changeColor('red');">Change text to red</button>
And see it!When you press the button the text in the div is change to red. magic!
var elemCN = document.getElementsByClassName(names);
where "names" is the class name given to one or more elements. So if we want to select all elements with a class="YYZ" then we usevar elemCN = document.getElementsByClassName('YYZ');
Or if we want to get all elements with class="YYZ" and class="limelight":var elemCN = document.getElementsByClassName('YYZ limelight');
Simple as that! var elemName = document.getElementsByName(name);
For an element with name="YYZ" we usevar elemName = document.getElementsByName('YYZ');
var elemTN = document.getElementsByTagName(name)
So, if we want to manipulate every div, we use 'div' as "name":var elemTN = document.getElementsByTagName('div')
Ok, folks... that is all for today.Please drop a line if you wish in the comments section below.
In the meantime, happy coding.
This post was written by: Franklin Manuel
Franklin Manuel is a professional blogger, web designer and front end web developer. Follow him on Twitter
0 Responses to “DOM: the document.getElement[s]By”
Enregistrer un commentaire