tags:

views:

87

answers:

2

Hi ,

i am having two divs ,

   <div id="input text">
      <fieldset>
      </fieldset>
    </div>

   <div id=1>

    </div>

in my JQuery i am trying to append some elements to the Div that is previous to #1 how to do so..

    $("<p>title</p>").appendTo(previous to 1 and inside fieldset );

since i am having many such divs i am trying to append using previous to 1 ??please suggest me...

+1  A: 
$("<p>title</p>").appendTo($("#1").prev("div"));
Philippe Leybaert
+1  A: 

Shortest version:

$("<p>title</p>").appendTo($("#1").prevAll("div:first").find("fieldset"));

Expanded version:

/* 1 */  var $destination = $("#1")
/* 2 */    .prevAll("div:first")
/* 3 */    .find("fieldset");
/* 4 */  $("<p>title</p>").appendTo($destination);
  1. Finds the element with id="1".
  2. prevAll gives us all previous elements that matches the selector ordered with the closest first. Thus div:first get's us the closest div. If we where to use prev instead, we'd not get anything if the previous element didn't match the selector.
  3. Find the fieldset.
  4. Add the new element.
svinto