2

I'm trying to dynamically place a button element next to some text but I'm getting the following in the DOM: Text next to button [object Object].

$btn = $('<button>').text('Button');
$('<div>').html('Text next to button ' + $btn).appendTo($('#test'))
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<div id="test"></div>

jsfiddle: https://jsfiddle.net/p43rft4q/1/

What am I doing wrong here and how can I fix this?

2
  • Where's the code? Commented Nov 17, 2017 at 23:10
  • Check the jsfiddle Commented Nov 17, 2017 at 23:11

3 Answers 3

3

You have to append the text and then the element. You were appending an object to text, which is why you were getting the [Object object].

$btn = $('<button>').text('Button');
$('<div>').append('Text next to button ').append($btn).appendTo($('#test'))
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<div id="test"></div>

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

Comments

2

Use this code

$btn = $('<button>').text('Button');
$('<div>').html('Text next to button ' + $btn[0].outerHTML).appendTo($('#test'))

Comments

-1
$btn = $('<button>').text('Button');
$('<div>').html('Text next to button ' + $btn.clone().wrap('<div>').parent().html()).appendTo($('#test'))

Basically what this is doing is creating a "clone" of the element, then wrapping the clone in a div, switching to the div (parent) then grabbing the html contents of that parent div.

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.