Reputation: 33
I am trying to insert content into a div using a jQuery variable.
What I'm trying to get is this.
<div class="results">
<div class="user-div">
<p>Hello world</p>
</div>
</div>
However it is rendering as:
<div class="results">
<div class="user-div"></div>'
<p>Hello world</p>
</div>
The following appears to be the correct syntax. It technically works if I use $('.user-div).append() but I'm trying to use a jQuery variable.
var $results = $('.results');
var $userDiv = $results.append('<div class="user-div"></div>')
$userDiv.append('<p>Hello world</p>');
In this case, the problem isn't appending a div to the DOM, but then also appending elements to that div using jQuery variables. Any suggestions are appreciated.
Upvotes: 3
Views: 6705
Reputation: 1654
Because append doesn't return reference to the appended content. It is referring to the same object i.e. results
after the first append, or no matter how many appends you would run. So try to use .appendTo()
var $results = $('.results');
var $userDiv = $results.append('<div class="user-div"></div>')
$( "<p>Hello world</p>" ).appendTo( ".user-div" );
Upvotes: 0
Reputation: 4061
var $results = $('.results');
var $userDiv = $('<div class="user-div"></div>').append('<p>Hello world</p>');
$results.append($userDiv);
You could also select child nodes using the context provided by the first selector:
var $results = $('.results');
$results.append( $('<div class="user-div"></div>');
var $userDiv = $('.user-div', $results); // We select children from the context provided by $results
$userDiv.append('<p>Hello world</p>');
Remember that $()
(or, more specific, jQuery()
) selects elements already in the DOM (or creates them if they don't exist). It's better to actually handle jQuery objects rather than HTML by itself. Makes it a lot more readable and easy to reference in the long term.
And at the end, I would end up doing something like this (way easier to understand):
var $results = $('.results');
var $userDiv = $('<div class="user-div"></div>');
var $text = $('<p>Hello world</p>');
$userDiv.append($text);
$results.append($userDiv);
Upvotes: 2