Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>getElementById</code> does only search for <em>element</em> nodes. You did create a text node, which has neither attributes nor an id - you just added a custom property to the JS object. Also, you did not append your node to the document, so it couldn't have been found in the DOM tree.</p> <p>You might want to read <a href="https://developer.mozilla.org/en-US/docs/Gecko_DOM_Reference/Introduction" rel="nofollow">an introduction to the DOM (at MDN)</a>, the <a href="http://www.quirksmode.org/dom/intro.html" rel="nofollow">introduction at quirksmode.org</a> or even the <a href="http://www.w3.org/TR/dom/" rel="nofollow">W3 standard itself</a> (especially the <a href="http://www.w3.org/TR/DOM-Level-3-Core/introduction.html" rel="nofollow">introduction section</a>)</p> <pre><code>function test() { var elem = document.createElement("span"); // Create an element var text = document.createTextNode("Hello"); // Create a textnode elem.appendChild(text); // add text to the element elem.id = "t"; // assign id to the element document.body.appendChild(elem); // Add it to the DOM } test(); var yourElement = document.getElementById("t"); // Get the element from the DOM alert(yourElement.textContent); // alerts "Hello" // you also could have alerted yourElement.firstChild.data - the content of the // textnode, but only if you had known that yourelement really has a firstchild </code></pre> <p>(<a href="http://jsfiddle.net/zDa2h/10/" rel="nofollow">Demo at jsfiddle.net</a>)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload