Ulikazu
Ulikazu

Reputation: 3

Move a paragraph after a div with .after (jQuery)

I am currently playing around with Codeacademy and I received a task, telling me to move a new paragraph, after a div. Heres what I did:

$('#one').after('<p>this is jquery</p>');

Now I want to move the new paragraph after another div, called #two, however, I am supposed to use .after, so it tells me. How would I go about moving the new paragraph, after the #two id.

Edit: Sorry, I am a beginner at this. Somehow, the stuff doesn't work in jsfiddle for me, I am most likely doing something wrong. However I will leave a couple of screenshots below:

https://i.sstatic.net/CbAmp.jpg

Upvotes: 0

Views: 2301

Answers (4)

Simrat Sidhu
Simrat Sidhu

Reputation: 1

$(document).ready(function() {
$('#one').after("<p>Let's see what we can add</p>");
$('p').after($('#two'));
});

This will work as it has complete flow of elements.

Upvotes: 0

Pete
Pete

Reputation: 58422

As you haven't set up the p as a separate variable I would do it like this:

$('#two').after($('#one').next('p'));

http://jsfiddle.net/PJff8/

My preferred way would be to set up the p as a variable and then you can move as much as you want without having to reselect it:

var p = $('<p>this is jquery</p>');
$('#one').after(p);
$('#two').after(p);

http://jsfiddle.net/PJff8/1/

Upvotes: 1

user2985029
user2985029

Reputation:

html

<div id="one">one</div>
<div id="two">two</div>

javascript

$('#one').after('<p>this is jquery</p>');
$('#two').after($("#one + p"));

example

Upvotes: 0

Richard
Richard

Reputation: 8280

If I understand correctly; you can use the next() in conjunction with insertAfter(), like so:

$('#one').after('<p>this is jquery</p>').next('p').insertAfter('#two');

jsFiddle Demo

Upvotes: 0

Related Questions