Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting content inside a div using .append()

Tags:

jquery

append

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.

like image 821
dustink1982 Avatar asked Mar 07 '26 09:03

dustink1982


1 Answers

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);
like image 68
Alejandro Iván Avatar answered Mar 08 '26 23:03

Alejandro Iván



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!