0

Everywhere I've searched I've only found ways to append a textnode after creating a new element. For example, they'll create a new paragraph (p) element, and afterwards they append the textnode to that new paragraph. But I want to add a textnode to an existing element (in my case, an empty span).

Link to code for example and clarification http://pastebin.com/K1EBMr4Z

<span class="span"></span> <!-- append textnode here -->
function newFunction(){
    var textnode = document.createTextNode("OK");

    // Append my `textnode` to the empty span here
}

Thanks in advance

try-catch-finally
  • 7,436
  • 6
  • 46
  • 67
kensington
  • 27
  • 5

5 Answers5

1

It's simple. Use appendChild method.

 function newFunction(){
    var textnode = document.createTextNode("OK");
    document.querySelector(".span").appendChild(textnode);
 }
Jakub Rożek
  • 2,110
  • 11
  • 12
1

As mentioned in the comment, you can add the text node as a child of the span using the appendChild() method.

For text you can also just set the innerHTML property of the span.

Both examples in a bin:

function newFunction(){
  var span = document.getElementById('my-span');
  var otherSpan = document.getElementById('my-other-span');

  span.innerHTML = 'Yo this is text';

  var textNode = document.createTextNode("OK");
  otherSpan.appendChild(textNode);
};

newFunction();

https://jsfiddle.net/9pmhan8L/1/

Ted A.
  • 2,264
  • 17
  • 22
  • is it possible to do this selecting a class or by tagname instead of an ID? – kensington Apr 21 '16 at 20:51
  • Absolutely possible. Replace `document.getElementById('my-span');` with `document.querySelector('.span')` to get the first element with `class="span"` or with `document.querySelector('span')` to get the first `` element. – Ted A. Apr 21 '16 at 22:39
0

If you give the span an id, you can get it using document.getElementById() and then change the html within that element. Here's a link to a SO that does this. Also, here's some docs for innerHTML and getElementByID.

Community
  • 1
  • 1
nscalf
  • 528
  • 5
  • 10
0

You need to select the node you want to append the textNode to first. Then, append the textNode to that selected node (in your case, the .span element).

<span class="span"></span>
function newFunction(){
    var textnode = document.createTextNode("Hello World!");

  // Select your existing element
  var empty_span = document.querySelector('.span');

  // Append the element
  empty_span.appendChild(textnode);
}

newFunction();

Example jsFiddle as well.

romellem
  • 5,792
  • 1
  • 32
  • 64
-1

Why not to use jQuery:

$('span').text('text');

or

$('span').html('<p>text</p>');

If you do not use it, use:

document.getElementsByTagName('span').innerHTM = '<p>text</p>';
arturas
  • 1,027
  • 1
  • 9
  • 26