0

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?

5 Answers 5

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

See the answer

$(shownBlocks[0]).replaceWith(hiddenBlocks[0]);
$(shownBlocks[1]).replaceWith(hiddenBlocks[1]);

Demo

Comments

0

You can use jquery:

$(selector).replaceWith(content)

Here is the fiddle with the code you provided.

http://jsfiddle.net/gwj0t7zy/21/

Comments

0

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]);
    });
});

Comments

0

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);
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.