Home » Jquery » javascript – How to select the inside of jQuery variable-Exceptionshub

javascript – How to select the inside of jQuery variable-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have some HTML in a jQuery object:

var $div = $(`
  <div class="myDiv">
    <p class="name"></p>
    <p class="data"></p>
  </div>`);

I want to change the content of the <p> elements, so I tried like this but in vain:

// Attempt #1
$div.".name".html("name here");

// Attempt #2
$div."> P".html("name here");

How can I use a selector to get the inside of jQuery variable?

How to&Answer:

Just as you would do when the elements are in the DOM, you need to use find() to retrieve elements within the object. Try this:

var $div = $(`<div class="myDiv">
  <p class="name"></p>
  <p class="data"></p>
</div>`);

$div.find('p').text('name here');
$div.appendTo('body');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>