1
<div id="main">
    <div id="abc">
        <div>
            This is the div to be replaced
        </div>
    </div>
    <div id="xyz" style="display:none">
        <div>
            This is the div replaced
        </div>
    </div>
</div>

I've given it like this

$('#main').children('div:eq(0)').css('display','none')
$('#main').children('div:eq(0)').replaceWith($('#xyz').html())

But, if I see the output, I get it as <div>This is the div replaced</div> alone and not the parent div of that i.e <div id="xyz">

3
  • 1
    Give the exact output you get in a code comment first. Commented May 8, 2013 at 13:09
  • Why are you trying to replace the div at all? It seems like show/hide/toggle would be sufficient. Commented May 8, 2013 at 13:09
  • The code is replaced with the code that is inside the xyz-div. Commented May 8, 2013 at 13:11

6 Answers 6

2

I think you are actually looking for toggle function.

Please check this fiddle

$('#main').click(function(){
    $('#main>div').toggle();
});
Sign up to request clarification or add additional context in comments.

Comments

1

http://api.jquery.com/html/

Essentially you're getting the innerHTML of $('#xyz'), rather than the entire tag itself.

Just do

$('#main').children('div:eq(0)').replaceWith($('#xyz'))

Comments

1
var isDisplayed = $("#main").find("#abc").css("display");
if(isDisplayed == "block"){
  $("#main").find("#abc").css("display","none");
  $("#main").find("#xyz").css("display","block");
}
else{
  $("#main").find("#abc").css("display","block");
  $("#main").find("#xyz").css("display","none");
}

Comments

1

maybe you're looking for this:

$('#main').children('div:eq(0)').replaceWith(xyz);

Comments

0

I think this should do what you want:

$('#main div:first').html($('#xyz').html())

3 Comments

<div id="main"> <div id="abc"> <div id="xyz" style="display:none"> This is the div replaced </div> </div> </div>
but i dont need the <div id="abc">
I just made that up briefly. I'm having trouble grokking exactly what you need. Perhaps if you could explain exactly what you would like to accomplish, I can provide some better insight.
0

Try this instead

$('#main').find('div:eq(0)').css('display','none');
$('#main').children('div:eq(0)').replaceWith($('#xyz'));

By specifing $('#xyz').html() you will only get the contents of the div.

For more info on replaceWith see jQuery docs

2 Comments

this takes the html content that is inside the <div id="xyz">, but i need it including the line <div id="xyz">
This will also take the div #xyz, it is the .html() that takes the contents

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.