0

I have three divs. How should I append a div onto an unknown div?

<div class="main" >
 <div id="drag-box" >
  <div id="" class=""> </div>
 </div>
  </div>

I want to append div on an unknown div which is come after drag-box div. I don't know which div comes after drag-box div. But there must be one div after drag-box div.

Clain Dsilva
  • 1,631
  • 3
  • 25
  • 34
user3030853
  • 17
  • 1
  • 1
  • 6

5 Answers5

1

try this

  $("#drag-box div:first-child").attr("id");
Neeraj Kumar
  • 1,058
  • 1
  • 9
  • 22
  • @MichalB. have you ever used jquery? Try to read this one before posting any thing http://api.jquery.com/first-child-selector/ – Neeraj Kumar Dec 10 '13 at 11:41
  • no worries, I perfectly understand what it does. OP asked how to append to/after a div without the id and you try to fetch the id for him... – Michal B. Dec 11 '13 at 07:30
1
$("#drag-box div:first-child").append("<span />");

or

$("#drag-box div").first().prepend("<span>first</span>");

For a complete answers, here it is working:

http://jsfiddle.net/dMUD3/

Alex
  • 8,875
  • 2
  • 27
  • 44
1

Instead of giving you a one liner I would like to give you an indepth solution.

A browser takes your html and parses what is called a DOM Tree out of it.

so if your html is .

<div class="a">
   <div class="foo"></div>
   <button class="foogle"></button>
</div>

The tree structure will become something like

 `-div.a
  |-div.foo
   `Button.foogle

You should actually look into DOM Api's at MDN

How DOM helps ?

With DOM api's you can actually access the unknown div using the reference to a known div. So if you actually understand your markup and its representation in DOM it should be pretty simple to get reference to nth child of an element;

You can access the child elements by the children attribute.

So

 // Get reference to the element.
 var parent = document.getElementById("drag-box");

 // Use the dom.
 var child_i_want = parent.children[0];
 // or there is another way
 var child_i_reallyWant = parent.firstElementChild;

There are solutions with jQuery but I feel its important for you to Understand basics of DOM even when there are helpful abstraction libraries in existance.

ShrekOverflow
  • 6,795
  • 3
  • 37
  • 48
0

You'll need the + selector. It applies to the object directly following. See here.

.drag-box + div {

}
Community
  • 1
  • 1
randak
  • 1,941
  • 1
  • 12
  • 22
  • This is for a div after it. Like `
    `. That is how I interpreted 'come after' but it appears you actually wanted the first child element.
    – randak Dec 10 '13 at 11:38
0
$('<div></div>').appendTo($('#drag-box div:first'))
webzar
  • 104
  • 8