JavaScript Output | SJB -->

This website uses cookies to ensure you get the best experience. More info...

Pages

JavaScript Output

There are several ways to generate output in JavaScript. Each and every scenario depends on our need. These are_

     innerHTML
document.write()
console.log()
window.alert()

innerHTML

Take a look at this code_
     <div>Virtual Species</div>
<p id="outputInnerHTML"></p>
<script>
var outputInnerHTML = document.getElementById("outputInnerHTML");
outputInnerHTML.innerHTML = "This is updated Virtual Species";
</script>
JavaScript access the HTML element "id" by using document.getElementById(id), and we can define the HTML content by innerHTML. We can change innerHTML of a HTML content to generate updated output in HTML.

document.write()

Take a look at this little script_
     <div>Virtual Species</div>
<button type="button" onclick="document.write('Virtual Species is replaced
with virtualspecies.com')"
>
CLICK</button></br>
<script>
document.write('This is for testing...');
</script>
Well, there are some controversies of using document.write(). Using it can create more bugs. First of all, it does not work with xHTML. By using document.write() after the page is fully loaded will delete all existing HTML content or will write a new page. However, it is very effective for testing. We can create an entire document by starting using document.write().

console.log()

Take a look at this code below_
     <div>Virtual Species</div>
<script>
console.log('This is Virtual Species...');
</script>
We use console.log() to display data while debugging. It prints the log of JavaScript, we can see it in action from browser's console window by entering COMMAND+SHIFT+J on Mac or CONTROL+SHIFT+J on Windows. We shouldn't use it on production sites that facing the web.

window.alert()

Take a look at the following snippet_ 
     <div>Virtual Species</div>
<script>
window.alert('This is Virtual Species...');
</script>
It displays an alert in a dialog box with predefined message.

No comments:

Post a Comment