Thursday 14 February 2013

JavaScript: innerHTML

   


In the following short post, we are going to take advantage of JavaScript and its innerHTML method.

Every DOM element can be manipulated using JavaScript. With the use of jQuery we can do great things, but if we need to do something more basic, it is probably better to use JavaScript directly, without the help of the aforementioned great library.

We can manipulate any DOM element using its id as selector together with document.getElementById. The advantage is that we can manipulate the inner html part of the element.
Let's see some example.

First example
Try the following example...
<script type="text/javascript">
function changeIH(){
    document.getElementById('theElem').innerHTML = '... enjoy yourself';
}
</script>
<div id='theElem'>Welcome to the Web Thought...</div>
<input type='button' onclick='changeIH()' value='What's next?'/>
Should I explain it? It looks quite simple... Try it for yourself and see how by clicking on the button the inner HTML of the div is changed.

Second example
This is different. Let's change the text according to a user input:
<script type="text/javascript">
function changeIH(){
    var userText = document.getElementById('userText').value;
    document.getElementById('theElem').innerHTML = userText;
}
</script>
<div id='theElem'>Chose a new text...</div>
<input type='text' id='userText' value='New Text' />
<input type='button' onclick='changeIH()' value='Submit'/>
Fill in the input box and press the button: the text "Chose a new text..." is replaced with the new text.
As you can see we can really do anything we want and manipulate the HTML inside a specific tag.

I could go on with many more example however I think we got to the point.
I leave the rest to your imagination.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.