I have a code like this:
<div class="usa_img_bg"> <div class="ca_title">Lorem Ipsum</div> <div class="img_box"> <div class="photo_room_f"> <p>Lorem Ipsum dolor si amet...</p> </div> </div> </div> <div class="usa_img_bg"> <div class="ca_title">Lorem Ipsum</div> <div class="img_box"> <div class="photo_room_f"> <p>Lorem Ipsum dolor si amet...</p> </div> </div> </div>
I want to get the ca_title
div and move it into the photo_room_f
div for every usa_img_bg
.
I use this code:
$.each($('.usa_img_bg'), function(index, element) { $(element).children(".ca_title").prependTo(".photo_room_f"); });
but it gets me all titles and puts them all on every usa_img_bg
div. How can I make it get only the ca_title
that's in every single usa_img_bg
?
Thanks in advance!
The selector you're using inside prependTo
is a standard jquery selector and it doesn't know you're only interested in the current element
, so it will be returning ALL elements on the page with a class of photo_room_f
.
Try something like this:
$.each($('.usa_img_bg'), function(index, element) {
var $el = $(element);
$el.children(".ca_title").prependTo($el.find(".photo_room_f"));
});
The issue in your code is that you are appending to all the .photo_room_f
elements, you need to find()
the one related to the .usa_img_bg
of the iteration. Try this:
$('.usa_img_bg').each(function(i, e) { var $room = $(this).find(".photo_room_f"); $(this).find(".ca_title").appendTo($room); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="usa_img_bg"> <div class="ca_title">Lorem Ipsum</div> <div class="img_box"> <div class="photo_room_f"> <p>Lorem Ipsum dolor si amet...</p> </div> </div> </div> <div class="usa_img_bg"> <div class="ca_title">Lorem Ipsum</div> <div class="img_box"> <div class="photo_room_f"> <p>Lorem Ipsum dolor si amet...</p> </div> </div> </div>
Try this:
$.each($('.usa_img_bg'), function() {
$(this).children(".ca_title").prependTo($(this).find('.photo_room_f'));
});
Try utilizing context
parameter of jQuery()
.prependTo($(".photo_room_f", element));
where element
is context
: .usa_img_bg
$.each($(".usa_img_bg"), function(index, element) { $(element).children(".ca_title").prependTo($(".photo_room_f", element)); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div class="usa_img_bg"> <div class="ca_title">Lorem Ipsum</div> <div class="img_box"> <div class="photo_room_f"> <p>Lorem Ipsum dolor si amet...</p> </div> </div> </div> <div class="usa_img_bg"> <div class="ca_title">Lorem Ipsum</div> <div class="img_box"> <div class="photo_room_f"> <p>Lorem Ipsum dolor si amet...</p> </div> </div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.