Tuesday, December 20, 2016

Javascript-3-Display/alert/write/set element content/ debugger


JavaScript can "display" data in different ways:


Writing into an alert box, using window.alert().

<body>


<script>window.alert(5 + 6);</script>

</body>

O/p: Displays a pop up alert dialog with "11" as below:










<body>


<script>window.alert("A"+5 + 6);</script>

</body>



O/p: Displays a pop up alert dialog with "A11" as below:

________________________________________

Write into HTML O/P using  document.write().
    • document.write() within a <script> tag
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>document.write(5 + 6);</script>
</body>

O/p: Prints a "11" on the webpage. Retains all other elements too.










    • document.write() without a <script> tag and as an event of a element replaces the entire document content. refer below.

<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button onclick="document.write(5 + 6)">Try it</button>
</body>

O/P: Prints a "11" and replaces all other elements too.









note: document.write() after an HTML document is fully loaded, will delete all existing HTML
________________________________________

Write into HTML element, using innerHTML.

  • display data" in HTML, (in most cases) you will set the value of an innerHTML property.
  • innerHTML is recommended over document.write() though both print values
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>document.getElementById("demo").innerHTML 5 + 6;</script>
</body>

________________________________________

Write into browser console, using console.log().
  • helps in debugging your webpage. open the webpage on a browser and enable the F12 key to see the values logged using the console.log() api as shown in the O/P section below:
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>console.log(5 + 6);</script>
</body>

O/P:




















___________________________________________________

debugger;


  • This keyword is used as a breakpoint in a webpage.
  • It can be placed at anypoint within the <script> tag to act as a breakpoint at that position.
  • However, the breakpoint gets activated only if the debugger of the browser if activated.
  • Example:
  • var x = 15 * 5;
    debugger;
    document.getElementbyId("demo").innerHTML = x;




________________________________________

No comments:

Post a Comment