Reputation: 63
I referred to the following example: http://jsfiddle.net/IlyaZ/gwj0t7zy/19/
I need to replace the first two divs (which have only block
class) with other two divs (which have s8-item-hidden
class).
Unfortunately, replaceWith
does not work as I expected. For example, shownBlocks[0].remove()
works fine.
Could you please advise how to fix the problem?
Upvotes: 0
Views: 74
Reputation: 5874
I think you have missed the jquery wrapper around shownBlocks. could you see whether it works
$(shownBlocks[0]).replaceWith(hiddenBlocks[0]);
$(shownBlocks[1]).replaceWith(hiddenBlocks[1]);
http://jsfiddle.net/IlyaZ/gwj0t7zy/19/
I have modified your code little bit.
$("#start").click(function () {
var shownBlocks = $("div.block:not('.s8-item-hidden')");
var hiddenBlocks = $("div.container > div.s8-item-hidden");
$(hiddenBlocks).each(function(index){
$(shownBlocks[index]).replaceWith(this);
});
});
Upvotes: 0
Reputation: 388316
shownBlocks[0]
returns a dom element reference which do not have replaceWith() method which is provided by jQuery wrapper, you can use .eq() method which return a jQuery wrapper reference to an element based on the passed index then call replaceWith()
$("#start").click(function () {
var shownBlocks = $("div.block:not('.s8-item-hidden')");
var hiddenBlocks = $("div.container > div.s8-item-hidden");
shownBlocks.eq(0).replaceWith(hiddenBlocks[0]);
shownBlocks.eq(1).replaceWith(hiddenBlocks[1]);
});
Demo: Fiddle
--
$("#start").click(function () {
var shownBlocks = $("div.block:not('.s8-item-hidden')");
var hiddenBlocks = $("div.container > div.s8-item-hidden");
shownBlocks.replaceWith(function (i) {
return $(hiddenBlocks).show();
})
});
Demo: Fiddle
Upvotes: 1
Reputation: 1372
Not really sure if that's what you're looking for, but this works:
$("#start").click(function () {
$(".block:not('.s8-item-hidden')").each(function(key, val){
$(this).replaceWith($('.s8-item-hidden')[key]);
});
});
Upvotes: 0
Reputation: 372
You can use jquery:
$(selector).replaceWith(content)
Here is the fiddle with the code you provided.
http://jsfiddle.net/gwj0t7zy/21/
Upvotes: 0