Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create and print h1 tags through JavaScript

I need to be able to create a function in JavaScript where all I need to do is type h1("hello") and it will print hello.

I want to avoid this method:

function h1(text) {
    document.write('<h1>'+text+'</h1>');
}

This is what I have:

function h1(text) {
    var div = document.createElement('div');
    document.appendChild(div);
    var h1 = document.createElement('h1');
    div.appendChild(h1);
    h1.createTextNode(text);
}
like image 912
crank123 Avatar asked Mar 08 '15 17:03

crank123


People also ask

How to create form Dynamically in JavaScript?

Approach 1: Use document. createElement() to create the new elements and use setAttribute() method to set the attributes of elements. Append these elements to the <form> element by appendChild() method. Finally append the <form> element to the <body> element of the document.

What is H1 tag in Javascript?

Browser support: Specifies document heading. There are predefined heading elements that allow document styling in HTML pages similar to Microsoft Office Word or other word processing software, H1 is the main heading and H6 is the deepest sub-heading element.

What will be printed in the H1 tag?

Your H1 Should Describe the Topic of Your Page Often, the H1 tag will be similar or the same as your title tag. Usually, the H1 tag will be the title of your blog post or article.


1 Answers

<script>
function myFunction(text) {
    var h = document.createElement("H1");
    var t = document.createTextNode(text);
    h.appendChild(t);
    document.body.appendChild(h);
}
</script>
like image 196
Vladu Ionut Avatar answered Sep 17 '22 18:09

Vladu Ionut