useranon
useranon

Reputation: 29514

how to append elements to the Div previous to the current element in JQuery

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...

Upvotes: 2

Views: 2595

Answers (2)

Svante Svenson
Svante Svenson

Reputation: 12488

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.

Upvotes: 3

Philippe Leybaert
Philippe Leybaert

Reputation: 171734

$("<p>title</p>").appendTo($("#1").prev("div"));

Upvotes: 1

Related Questions