henrywright
henrywright

Reputation: 10250

Traversing the DOM tree with jQuery

<div class="media">

    <div class="pull-left">

    </div>

    <div class="media-body">

        <div class="content">

        </div>

        <div class="news">

            <div class="sub">

            </div>

            <!-- insert here -->

        </div>

    </div>

</div>

<div id="current">

</div>

I am trying to traverse the DOM tree using jQuery. My DOM is described above. My starting point is id="current". I'd like to insert some data where I have written <!-- insert here -->

So far I've tried this which didn't work: $(data).appendTo($("#current").prev("div"));. Hoping somebody can help?

Please note: I have multiple .media, .pull-left, .media-body, .content, .news and .sub divs elsewhere on the page.

Upvotes: 0

Views: 60

Answers (2)

Ken Herbert
Ken Herbert

Reputation: 5236

To append only to the previous sibling's ancestor with class equal to news try the following:

$(data).appendTo($("#current").prev(".media").first().find(".news"));

jsFiddle

Upvotes: 2

Nick Rolando
Nick Rolando

Reputation: 26177

$(data).appendTo($("#current").parent().find(".news"));

http://jsfiddle.net/5pLCq/1/

Upvotes: 2

Related Questions