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>
}
@user899043: Exactly; tags can't go directly in JavaScript code.
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.
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.
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.
You will either have to document.write
it or use the Document Object Model:
document.write
<script type="text/javascript">
if(document.getElementById('number1').checked) {
document.write("<h1>Hello member</h1>");
}
</script>
<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>
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With