Javascript get element by id

Twitter Facebook Pinterest Google+ Stumbleupon LinkedIn


Javascript is probably the most awesome tool a web developer can use to make a website both functional and look nice. Javascript has also evolved over the years with the DOM it has become much easier to develop.

One useful piece of code I always end up using when writing Javascript is getElementById, the way Javascript evolved has given it much more compatibility with different browsers and in turn means you need less code to do more.

getElementById allows you to modify any html element with a given ID. so for example if you have a <div> with the ID jstest it might look like this

<div id=”jstest”>howdy</div>

Using document.getElementById(‘jstest’) we can modify this element dynamically with javascript changing anything from its appearance or position with styling or use it within our javascript code.

using document.getElementById(‘jstest’).innerHTML we could change or get the contents of the div.

Another pretty awesome use for the getElementById method would be to change the style of an element dynamically, maybe you want it to disappear when clicked or have a border when highlighted.

To change the background of an element we could use document.getelementById(‘jstest’).style.background-color = ‘#dedede’  this will work with any styling you could apply to an element.

If you are like 90% of the old school web developers I know you probably don’t like using javascript but the modern DOM it is couldn’t be easier.


Posted by Adi on April 23, 2009

Twitter Facebook Pinterest Google+ Stumbleupon LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *