Jimenemex Jimenemex - 4 months ago 7
Javascript Question

Inserting a div after another

I'm trying to 'move' a

div
from one location to another. I'm using
.after
, but it doesn't call the method? What am I doing wrong?



var row = $('<div class="row">Another row inserted</div>');
$('.container').append(row);

$('.button').click(function() {
$('.row').addClass('row-changed');
$('.container:eq(2)').after(row);
});

.row {
color: blue;
}
.row-changed {
color: red;
}

<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<div class='container'>
<button class='button'>Move</button>
<div class='row'>Row here</div>
<div class='row'>Row here</div>
<div class='row'>Row here</div>
<div class='row'>Row here</div>
<div class='row'>Row here</div>
</div>




Answer

If you're trying to select the nth child of the .container, .container:eq(2) will not work since it is trying to select the second .container, not the second child of the .container. You can use the :nth-child() selector instead.

jQuery

$('.button').click(function() {
    $('.row').addClass('row-changed');
    $('.container > div:nth-child(2)').after(row);
});

var row = $('<div class="row">Another row inserted</div>');
$('.container').append(row);

$('.button').click(function() {
	$('.row').addClass('row-changed');
	$('.container > div:nth-child(2)').after(row);
});
.row {
  color: blue;
}
.row-changed {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
  <button class='button'>Move</button>
  <div class='row'>Row here</div>
  <div class='row'>Row here</div>
  <div class='row'>Row here</div>
  <div class='row'>Row here</div>
  <div class='row'>Row here</div>
</div>

JSFiddle