getAttribute(), setAttribute(), and removeAttribute()

Creator:
bfr

getAttribute(), setAttribute(), and removeAttribute()

getAttribute()

getAttribute() returns an attribute's value. It can be very useful and is really easy to learn. Here's the syntax: getAttribute(attribute) Here is an example for a document that had a table with a width of 300 and an id of "myTable":

<script type="text/javascript">
var theTablesWidth = document.getElementById("myTable").getAttribute("width");
</script>

The example above would make the variable theTablesWidth be equal to 300 because the table's width was 300.

setAttribute()

setAttribute() changes an attributes value by giving it a new one. It is extremely userful. Here's the syntax: setAttribute(attribute, theNewValue) Here is an example for a document that had a table with a width of 300 and an id of "myTable" (the same situation as before) >>

<script type="text/javascript">
document.getElementById("myTable").setAttribute("width","200");
</script>

The above example would change the table's width to 200. Here is another example for lets say I had a hyperlink with an id of "myLink" that linked to http://ssdesigns.proboards17.com:

<script type="text/javascript">
document.getElementById("myLink").setAttribute("href","http://www.solidsnakedesigns.com");
</script>

The above script would make the link that used to go to http://ssdesigns.proboards17.com now go to http://www.solidsnakedesigns.com.

removeAttribute()

removeAttribute() removes an attribute. It may be useful if you want something to change to the default setting. Here is an example for a document that had a table with a and an id of "myTable" (the same situation as before) >>

<script type="text/javascript">
document.getElementById("myTable").removeAttribute("width");
</script>

The above example would remove the table's width attribute, setting it to the default width.

Conclusion

Combining the powers of getAttribute(), setAttribute(,), removeAttribute() can give you pretty complex websites. Maybe you use getAttribute() to get a table's width and store it into a variable, and then use setAttribute() to increase the table's width by 100 pixels.

Hope you all enjoyed the tutorial and happy coding!

Description:
Teaches the basics of getAttribute(), setAttribute(), and removeAttribute(), and includes examples.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options