简体   繁体   中英

Using createElement in JavaScript, how to add <p> and <span> inside of <div>?

I'm trying to create sentences with a box next to them, where text can be dragged and dropped in the box.

So I want to create this HTML markup using only javascript:

<div>
  <p>Data1<span class = "smallBox droppable"></span></p>
  <p>Data 2<span class="smallBox droppable"></span></p>
</div>

That code functions and I'm able to drag and drop text into the boxes that are placed alongside the words "Data1" and "Data 2".

So far I have:

 var data2 = ['one', 'two', 'three'] function dragDrop2(arr) { var length = arr.length; var list = document.createElement("div"); for (var i = 0; i < length; i++) { var paragraph = document.createElement("p"); var spanning = document.createElement("span"); spanning.classList.add("smallBox", "droppable", "draggable"); paragraph.appendChild(document.createTextNode(arr[i])); paragraph.appendChild(spanning); list.appendChild(paragraph); } return list; } document.getElementById("example").appendChild(dragDrop2(data2)); 
 <div id="example"></div> 

Right now, given my current javascript/html attempt, the drag/drop part isn't working in the boxes, and the I don't think the "span" tag is insie of the "p" tag, as my box is underneath each sentence.

If anyone can help me, I'd appreciate it! Also, is there something that I can do to see the markup that is being created?? For example, create an alert that will show all the html markup, beginning at the original 'div id="example"?? (.html???)

 var data2 = ['one', 'two', 'three'] function dragDrop2(arr) { var length = arr.length; var list = document.createElement("div"); for (var i = 0; i < length; i++) { var paragraph = document.createElement("p"); var spanning = document.createElement("span"); spanning.classList.add("smallBox", "droppable", "draggable"); spanning.appendChild(document.createTextNode(arr[i])); paragraph.appendChild(spanning); list.appendChild(paragraph); } return list; } document.getElementById("example").appendChild(dragDrop2(data2)); $( "span" ).draggable().droppable(); 
 p { border: 1px solid #000; padding: 20px; } span { background-color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div id="example"></div> 

I'm assuming you're using draggable and droppable from jquery ui .

You must execute the draggable and droppable functions after creation of elements.

Another key point is to change this:

paragraph.appendChild(document.createTextNode(arr[i]));

to this:

spanning.appendChild(document.createTextNode(arr[i]));

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