0

I have a web page with a set of buttons across the top. I am writing a function to place a form to the right of the rightmost button when it is clicked. I am using the following JavaScript code.

var optionsForm = document.createElement("form");
optionsForm.setAttribute('method',"post");
optionsForm.style.display = "inline";
MakeDropDown(optionsForm);  // Make drop-down list element
document.getElementsByTagName('body')[0].appendChild(optionsForm);

However it places the form/drop-down list at the bottom of the page instead of just to the right of the buttons at the top. I would prefer not to have to use absolute positioning since I want the form to be just to the right of the right-most button and there may be a different number of buttons.

dtech
  • 13,741
  • 11
  • 48
  • 73
OtagoHarbour
  • 3,969
  • 6
  • 43
  • 81

3 Answers3

3

It places it at the bottom because you are appending it to the body.

If you want it to appear just after a particular button, then you need to:

  1. get that button
  2. get that button's parentNode
  3. test to see if the button is the last child in its parent or not
  4. appendChild or insertBefore the form into that parent

If you want it to display inline with the button, then you also need to make sure that the button is displayed inline (as well as the new form) and that there is nothing else that will disrupt the layout (such as floats).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

That's because you are appending the form to your body: document.getElementsByTagName('body')[0]. You need to append it after your button with something like: document.getElementById('my-buttons-container').appendChild(optionsForm);.

Hope this helps!

cortex
  • 5,036
  • 3
  • 31
  • 41
1

You should append the form after those buttons. To do that you need to get the parentNode of those buttons, and use buttonNode.insertBefore(buttonsParent, buttons) Have a look at this: Javascript Append Child AFTER Element

Community
  • 1
  • 1
Mimo
  • 6,015
  • 6
  • 36
  • 46