简体   繁体   中英

Add firstchild to newly added element

I need to create a new child to an existing element. The question add onclick event to newly added element in javascript helped me a lot.

I just can not define it as the first child. I can place it using position , but this is still insufficient. I searched on sites about JavaScript, but I found nothing.

Here is my code:

if( !document.getElementById('callbackButton')){
  callback = function(){
  var button = document.createElement('button');
  button.id= 'callbackButton';
  var textbutton =document.createTextNode("Liste des années d'étude");
  button.appendChild(textbutton );
  button.style.position='absolute';
  button.style.top="60px";
  button.style.left="45px";
  button.style.width="200px";
  button.style.height="18px";
  button.onclick = function(){
    getElementsByIdStarWith('etageres-virtuelle')[0].innerHTML = oldInnerHtml;
    document.getElementById('etageres-virtuelles-etudes-germaniques').innerHTML =      oldInnerHtml;   
    wrapPager();
  };
  document.getElementById('etageres-virtuelles-etudes-germaniques').appendChild(button);
 };

This code works very well.

But this code doesn't work:

document.getElementById('etageres-virtuelles-etudes-germaniques').firstChild.nodeValue = button;
document.getElementById('etageres-virtuelles-etudes-germaniques').firstChild.nodeData = button;

This is not what I want. I want to display this new element on first place.

Any help would be appreciated. Thank.

Try this (untested):

var yourEl = document.getElementById('etageres-virtuelles-etudes-germaniques');
yourEl.insertBefore(button, yourEl.firstChild);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM