3

I'm trying to get this running

$('#info').replaceWith('<div id="infobox" class="reveal-modal">'+$('#info').contents()+'<a class="close-reveal-modal">&#215;</a></div>');

but It just gives me [object Object]. As I only replace it with $('#info').contents() things work fine.

1
  • 1
    Well, $('#info').contents() is an object and the default string representation of an object is [object Object]. You cannot just concatenate strings with arbitrary objects. Commented Aug 24, 2012 at 17:56

4 Answers 4

4

Try:

$(function(){
    var content = $('#info').get(0).outerHTML;
    $('#info').replaceWith('<div id="infobox" class="reveal-modal">'+content+'<a class="close-reveal-modal">&#215;</a></div>');
})

The $('#info').get(0).outerHTML returns <div id="info">anything</div>. But if just want the content, use $('#info').html(), that returns anything.

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

Comments

2

If you're trying to maintain the existing content and place it inside an outer div try using wrap() and you can call after() to adding the closing anchor.

$('#info').wrap('<div id="infobox" class="reveal-modal">')
    .after('<a class="close-reveal-modal">&#215;</a>')

Working example: http://jsfiddle.net/hunter/qU4s3/


Could also be written like this:

$('#info')
    .wrap($('<div>', { id: "infobox", "class": "reveal-modal"}))
    .after($('<a>', { "class": "close-reveal-modal", html: "&#215;" }));

Working example: http://jsfiddle.net/hunter/qU4s3/2/

3 Comments

One thing though, .append should be .after, and wrap should include it.
Your updated version looks even better and makes sense to me, testing.
+1 Best answer so far as it doesn't have to parse HTML unnecessarily.
1

.contents() returns a jQuery object, what you want is .text() or .html() depending on if #info contains other elements.

$('#info').replaceWith('<div id="infobox" class="reveal-modal">'+$('#info').text()+'<a class="close-reveal-modal">&#215;</a></div>');

Comments

0

starts with $('#info').contents(). <-- like this

1 Comment

Please explain how this solves the problem? What is the trailing dot for? If you'd just insert it into the OP's code, you'd get a syntax error.

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.