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

Time:12-30

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?

CodePudding user response:

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.

CodePudding user response:

There are a few things to note:

  • Your HTML does not have a 'anchor' defined
  • You are creating a p element (paragraph)- it will render on a separate line unless you specify the style/css otherwise. You can use a span to achive what you stated. See below:

label_element = document.createElement('label'); // Create a label element
label_node = document.createTextNode('Label:'); // Add a text node to the label
label_element.appendChild(label_node);

span_element = document.createElement('span'); // Create a span element
span_node = document.createTextNode('This text should be next to label'); // Add a text node to span
span_element.appendChild(span_node);

//label_element.appendChild(span_element)

document.getElementById('anchor').appendChild(label_element)
document.getElementById('anchor').appendChild(span_element)
<div id="anchor">

</div>

CodePudding user response:

try the following code

HTML

 <div id="main">

 </div>

JS

 document.getElementById('main').innerHTML=
     "
        <div>
            <label>Label:</label>
            <span>This text should be right beside the label</span>
        </div>
    "
  • Related