Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend some innerHTML to a div in Native Javascript

Tags:

javascript

Please bear with me on this question; I have only recently started coding in Javascript and for this reason I would like a strong foundation before breaking into jQuery.

I have the following Javascript code:

var app = {
  text: document.getElementById('text'),
  output: document.getElementById('output'),
  createDiv: document.createElement('div')
};

function postData(){
  app.output[0].appendChild(app.createDiv.firstChild);
  app.createDiv.classname = 'text';
  document.getElementsByClassName('username').innerHTML += app.text.value;
}

onClick I want the value of app.text to print (using innerHTML) ABOVE the output div. Any ideas or questions? Sorry if I am being vague or not making sense, I have been staring at this for 4 hours now and am probably just burned out!

like image 615
Andrew Hill Avatar asked May 11 '26 22:05

Andrew Hill


2 Answers

You'll have to create a text node and insert it before each element in the NodeList returned by document.getElementsByClassName:

var node = document.createTextNode(app.text.value);
var elements = document.getElementsByClassName('username');

for (var i = 0; i < elements.length; i++) {
    var elem = elements[i];
    elem.parentNode.insertBefore(node.cloneNode(), elem)
}

And just to tempt you with the jQuery version:

$('.username').before(app.text.value);
like image 179
Blender Avatar answered May 13 '26 11:05

Blender


I'm not sure what you're asking, but I see the following problems with your code:

  • app.output[0]: there should be no [0], app.output is already an element (you got it by id). So use app.output.appendChild(app.createDiv.firstChild);. Still, this makes no sense; as Barmar said, you just created that div, so it doesn't have any children at that point.

  • app.createDiv.classname: should be className

  • document.getElementsByClassName('username').innerHTML: this returns multiple elements, maybe you want document.getElementsByClassName('username')[0].innerHTML?

like image 27
bfavaretto Avatar answered May 13 '26 12:05

bfavaretto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!