Search code examples
javascripthtmldomlabelgetelementbyid

How can I use javascript to create a div with elements inside of it?


I would like to create the following structure:

<div>
  <label>Label:</label>
  <p>This text should be right beside the label</p>
</div>

So the results would look something like:

Label: Here is the text

I have tried doing using the following:

label_element = document.createElement('label')
p_element = document.createElement('p')

label_node = document.createTextNode('text')
p_node = document.createTextNode('text2')

label_element.appendChild(p_element)

document.getElementById('anchor').appendChild('label_element')

The above returns:

Label:

Here is the text

How can I make them together? An alternative for me would be to concate strings into one, but what if I want to have an input field right beside the label field?


Solution

  • A p element is a paragraph element and will render with space above and below.

    To get inline text, within the Label element, use a span element instead.