w3resource

HTML5: How to specify the media type of the script?

Go to Exercise page

Solution:

HTML Code:

<!DOCTYPE html><!-- Define document type as HTML5 -->
<html><!-- Start of HTML document -->
<head><!-- Start of head section -->
<meta charset="utf-8"><!-- Define character encoding -->
<title>How to specify the media 
type of the script</title><!-- Title of the document -->
</head><!-- End of head section -->
<body><!-- Start of body section -->
<p id="output">Click Me</p><!-- Define a paragraph with an id for interaction -->
<script type ="text/javascript"><!-- Start of JavaScript script with specified media type -->
function w3r(){  // Define a JavaScript function named "w3r"
console.log('This is an example of script element');  // Output a message to the browser console
}   
var el = document.getElementById('output'); // Get the element with the id "output"
el.addEventListener("click", w3r, false); // Add a click event listener to the element, calling the "w3r" function
</script><!-- End of JavaScript script -->
</body><!-- End of body section -->
</html><!-- End of HTML document -->

Explanation:

  • This HTML code demonstrates how to specify the media type of a script using the type attribute within the <script> element.
  • The <script> element is used to define client-side JavaScript code.
  • The type attribute specifies the media type of the script content, which in this case is "text/javascript".
  • The text/javascript media type indicates that the content of the <script> element is JavaScript code.
  • The JavaScript code inside the <script> element defines a function named w3r() and adds a click event listener to an HTML element.
  • This example demonstrates the use of the type attribute to explicitly declare the media type of the script content, although it's not strictly necessary for JavaScript in HTML5.
  • Live Demo:

    See the Pen script-type-answer by w3resource (@w3resource) on CodePen.


    See the solution in the browser

    Supported browser

    Firefox logo Chrome logo Opera logo Safari logo Internet Explorer logo
    Yes Yes Yes Yes Yes

    Go to Exercise page

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.