crank123
crank123

Reputation: 251

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);
}

Upvotes: 8

Views: 33043

Answers (3)

Divyamshu Gupta
Divyamshu Gupta

Reputation: 21

The better way would be to Import ElementsJS and just reference each element in it.

// Create H1 Without Class
var root = document.getElementById("root");
create_element('h1',null, root, "This is a H1 Text");


// Create H1 With Class
var root = document.getElementById("root");
create_element('h1',{'class':'h1css'}, root, "This is a H1 Text");
.h1css {
  background-color : grey;
  height: 50px;
  position: absolute;
  }
<script src="https://elementsjs.blob.core.windows.net/public/create-elements.js"></script>
<body id="root"></body>

Upvotes: 1

Vladu Ionut
Vladu Ionut

Reputation: 8193

<script>
function myFunction(text) {
    var h = document.createElement("H1");
    var t = document.createTextNode(text);
    h.appendChild(t);
    document.body.appendChild(h);
}
</script>

Upvotes: 24

T.J. Crowder
T.J. Crowder

Reputation: 1075319

You don't need the div, and you need to append to document.body, not document. Also, elements don't have a createTextNode, that's a method on document:

function h1(text) {
    var h1 = document.createElement('h1');
    h1.appendChild(document.createTextNode(text));
    document.body.appendChild(h1);
}

Live example:

function h1(text) {
    var h1 = document.createElement('h1');
    h1.appendChild(document.createTextNode(text));
    document.body.appendChild(h1);
}
var counter = 0;
var timer = setInterval(function() {
  ++counter;
  h1("Hi #" + counter);
  if (counter == 5) {
    clearInterval(timer);
  }
}, 500);

More to explore:

Upvotes: 5

Related Questions