0

I've searched around using Google and Stack Overflow, but I haven't seemed to find a answer to this. I want to write text inside a <div> element, using JavaScript, and later clear the <div> element, and write more text into it. I am making a simple text adventure game.

This is what I am trying to do:

<DOCTYPE!HTML>
    <body>
        <div class="gamebox">
            <!-- I want to write in this div element -->

        </div>
    </body>

As a new user to JavaScript, how would I be able to write inside the div element gamebox? Unfortunately, my JavaScript skills are not very good, and it would be nice if you can patiently explain what happens in the code.

4
  • @mshsayem I believe he wants to write text to the div, not create a div. Commented Mar 1, 2014 at 9:28
  • @JordanFitz Yes, I want to write text inside the div. How do I accomplish that? I'm only in 8th grade, I have no professional experience with web development whatsoever, so if you would take some time to explain what happens, that'll be great. From what I can tell, document.createElement("div") creates a new html element div at document.html, correct? Commented Mar 1, 2014 at 9:31
  • Check out my answer below. Commented Mar 1, 2014 at 9:31
  • Try not to use those DOM node method to build it, use string building instead, HTML string building uses less memory. Commented Mar 1, 2014 at 9:38

3 Answers 3

4

You can use querySelector to get a reference to the first element matching any CSS selector. In your case, a class selector:

var div = document.querySelector(".gamebox");

querySelector works on all modern browsers, including IE8. It returns null if it didn't find any matching element. You can also get a list of all matching elements using querySelectorAll:

var list = document.querySelectorAll(".gamebox");

Then you access the elements in that list using 0-based indexes (list[0], list[1], etc.); the length of the list is available from list.length.

Then you can either assign HTML strings to innerHTML:

div.innerHTML = "This is the text, <strong>markup</strong> works too.";

...or you can use createElement or createTextNode and appendChild / insertBefore:

var child = document.createTextNode("I'm text for the div");
div.appendChild(span); // Put the text node in the div

Those functions are found in the DOM. A lot of them are now covered in the HTML5 specification as well (particularly Section 3).

Sign up to request clarification or add additional context in comments.

4 Comments

From what I gather .querySelector / .querySelectorAll are especially useful for more complex selections like ".gamebox .descendantclass" and similar selections. Looking at a jsperf.com/… it seems a lot slower than getElementsByClassName for single class selections (93% slower it shows). Downside is IE8 and lower indeed do not seem to support getElementsByClassName (caniuse.com/getelementsbyclassname) ;(
@DaniëlKnippers: While that's a substantial absolute performance delta, at more than three-quarters of a million queries/second, I very much doubt there's any real-world, perceptible difference. Whereas of course, QS/QSA are dramatically more useful, and supported by IE8, which is and will remain in general use for some time. :-)
@DaniëlKnippers: Of course, arguing it the other way, if one were worried about the performance (I can't imagine what one would be doing where it would matter, but...) and really wanted to use getElementsByClassName, one could do this: if (!document.getElementsByClassName) { document.getElementsByClassName = function(cls) { return document.querySelectorAll("." + cls); }; } (pastie.org/8814392) :-) Then you'd get the gain on engines that had it; IE8 is a dog anyway.
@T.J.Crowder Agreed, it probably does not come in to play but I found it interesting to be such a big difference. I'd guess the performance difference between the two would be very similar in case of single class selections, but it's not -- though as you pointed out for all practical cases the difference is probably negligible.
0

Select a single element with document.querySelector or a collection with document.querySelectorAll.

And then it depends, on what you want to do:

Writing Text into the div or create an Element and append it to the div.

Comments

0

Like mentioned getElementsByClassName is faster. Important to know it when you use this you get returned an array with elements to reach the elment you want you specify its index line [0], [1]

var gameBox = document.getElementsByClassName('gamebox')[0];

Here how you can do it

    //returns array with elements
    var gameBox = document.getElementsByClassName('gamebox');

//inner HTML (overwrites fsd) this can be used if you direcly want to write in the div
    gameBox[0].innerHTML ='<p>the new test</p>';



//Appending when you want to add extra content

    //create new element <p>
    var newP = document.createElement('p');


    //create a new TextNode
    var newText = document.createTextNode("i'm a new text");

    //append textNode to the new element
    newP.appendChild(newText);


    //append to the DOM
    gameBox[0].appendChild(newP);

https://developer.mozilla.org/en-US/docs/Web/API/document.createElement https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName

4 Comments

just a little to late xD
Its ok. I'll combine this with the answer by T.J Crowder, to accomplish what I've been trying to do. :D From what I can tell, every time I use the elm.innerhtml, it replaces the current text, right? For example, if I do: elm.innerHTML = "first text" elm.innerHTML = "second text" I'll replace the current "first text" with "second text", right?
w3schools is a notoriously poor reference. Much better to go to primary references (such as the DOM specs I liked) or a better meta-reference, like MDN.
Yes thats right and the sources given by T.J Crowder are better. But I just wanted to give a quick example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.