Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML tag inside JavaScript

Tags:

javascript

I am trying to use some HTML tag inside JavaScript, but the HTML tag does not work. How can U use an HTML tag inside JavaScript? I wanted to use h1 but did not work.

if (document.getElementById('number1').checked) {
  <h1>Hello member</h1>
}
like image 430
user899043 Avatar asked Aug 17 '11 17:08

user899043


People also ask

Can you write HTML tag inside the JavaScript?

@user899043: Exactly; tags can't go directly in JavaScript code.

How do you link JavaScript and HTML?

We can link JavaScript to HTML by adding all the JavaScript code inside the HTML file. We achieve this using the script tag which was explained earlier. We can put the <script></script> tag either inside the head of the HTML or at the end of the body.

What is the HTML tag under which one can write JavaScript code?

The HTML <script> tag is used to define a client-side script (JavaScript). The <script> element either contains script statements, or it points to an external script file through the src attribute.

Where do you put JavaScript tags in HTML?

In HTML, JavaScript code is inserted between <script> and </script> tags. You can place any number of scripts in an HTML document. Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.


2 Answers

You will either have to document.write it or use the Document Object Model:

Example using document.write

<script type="text/javascript">
if(document.getElementById('number1').checked) {
    document.write("<h1>Hello member</h1>");
}
</script>

Example using DOM

<h1></h1> <!-- We are targeting this tag with JS. See code below -->
<input type="checkbox" id="number1" checked /><label for="number1">Agree</label>
<div id="container"> <p>Content</p> </div>

<script type="text/javascript">
window.onload = function() {
    if( document.getElementById('number1').checked ) {
        var h1 = document.createElement("h1");
        h1.appendChild(document.createTextNode("Hello member"));
        document.getElementById("container").appendChild(h1);
    }
}
</script>
like image 163
Richard JP Le Guen Avatar answered Oct 07 '22 11:10

Richard JP Le Guen


<html>
 <body>
  <input type="checkbox" id="number1" onclick="number1();">Number 1</br>
  <p id="h1"></p>
   <script type="text/javascript">
    function number1() {
    if(document.getElementById('number1').checked) {

      document.getElementById("h1").innerHTML = "<h1>Hello member</h1>";
         }
    }
   </script>
 </body>
</html>
like image 30
user7644865 Avatar answered Oct 07 '22 09:10

user7644865