jQuery on click move a div after() the parent

1.1k views Asked by At

In the following code, how can I move the <div class="move">I was moved to the parent.</div> after the parent of the element I click, when I click Add New.

I have everything right, but I cannot do the part where I need to move it after() the parent.

Can you please help?

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Side bar poll thingy</title>
<script type="text/javascript" src="http://localhost/site/scripts/jQueryCore.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('.add').click(function() {
    $("#container").find('.flag, .edit, .delete').remove();
    $(this).parent("div").after(".move");

    });
});
</script>
</head>
<body>
<div id="container">
    <div class="h1" data-id="1">Teachers <span class="add" data-id="US01">Add New</span></div>
    <div class="h2" data-id="2">Who is your favorite Math teacher? <span class="add" data-id="US02">Add New</span></div>
        <br>
    <div class="h1" data-id="8">Restaurants <span class="add" data-id="US10">Add New</span></div>
    <div class="h2" data-id="9">Which is your favourtie restaurant in town? <span class="add" data-id="US20">Add New</span></div>

    <div class="move">I was moved to the parent.</div>
</div>
</body>
</html>
3

There are 3 answers

0
jasonslyvia On BEST ANSWER

try this fiddle http://jsfiddle.net/QP3MZ/

$(document).ready(function () {
    $('.add').click(function () {
        $("#container").find('.flag, .edit, .delete').remove();
        var $move = $('#container .move');
        $(this).parent("div").after($move);
    });
});
0
Ram On

.after() doesn't accept selectors, currently you are inserting .move string after the selected element. You can use .insertAfter() method instead:

$(".move").insertAfter(this.parentNode);

http://jsfiddle.net/RYzpG/

0
Swashata Ghosh On

This code should work.

$(document).ready(function() {
    $('.add').click(function(e) {
        e.preventDefault();
        $("#container").find('.flag, .edit, .delete').remove();
        $('.move').insertAfter($(this).parent());
        //Or (Note we have to pass a jQuery element inside after, if we pass string then it will copy the string instead)
        //$(this).parent('div').after($('.move'));
    });
});

Also here is a jsfiddle. The reason why yours wasn't working is you are passing a string inside the .after, which jQuery would treat as an HTML string. You had to pass a jQuery element or DOM element. See it here.