Output (getElementById) in Javascript

Output (getElementById)

Output (getElementById)

The last method is the most powerful and the most complex (but don't worry, it's really easy!).

Everything on a web page resides in a box. A paragraph () is a box. When you mark something as bold you create a little box around that text that will contain bold text. You can give each and every box in HTML a unique identifier (an ID), and Javascript can find boxes you have labeled and let you manipulate them. Well enough verbiage, check out the code!



<html>
  <head>
  </head>
  <body>
     <div id='feedback'></div>
     <script type='text/javascript'>
        document.getElementById('feedback').innerHTML='Hello World!';
     </script>
  </body>
</html>

The page is a little bigger now but it's a lot more powerful and scalable than the other two. Here we defined a division and named it "feedback". That HTML has a name now, it is unique and that means we can use Javascript to find that block, and modify it. We do exactly this in the script below the division! The left part of the statement says on this web page (document) find a block we've named "feedback" (getElementById('feedback')), and change its HTML (innerHTML) to be 'Hello World!'.
We can change the contents of 'feedback' at any time, even after the page has finished loading
(which document.writeln can't do), and without annoying the user with a bunch of pop-up alert boxes (which alert can't do!).

It should be mentioned that innerHTML is not a published standard. The standards provide ways to do exactly what we did in our example above. That mentioned, innerHTML is supported by every major Browser and in addition innerHTML works faster, and is easier to use and maintain. It's, therefore, not surprising that the vast majority of web pages use innerHTML over the official standards.

While we used "Hello World!" as our first example, its important to note that, with the exception
of <script> and <style>, you can use full-blown HTML. Which means instead of just "Hello World" we could do something like this…
 

<html>
  <head>
  </head>
  <body>
     <div id='feedback'></div>
     <script type='text/javascript'>
        document.getElementById('feedback').innerHTML='<P><font color=red>Hello
World!</font>';
     </script>
  </body>
</html>


In this example, innerHTML will process your string and basically redraw the web page with thenew content. This is a VERY powerful and easy to use concept. It means you can basically take an empty HTML element (which our feedback division is) and suddenly expand it out with as much HTML content as you'd like.

Comments

Popular posts from this blog

How to Connect Android to Multiple WiFi Hotspots

Free URL Submission in Search Engines and Web Directories

Connectify Dispatch & Hotspot Pro v4.0 (Full & Free Download)