1

I'm trying to create table elements using jQuery but it won't return the first element stored or created:

$("<tr>",{class: "ertert"}).append($("<td>",{text:"adfsadfasdf"})).html()

// "<td>adfsadfasdf</td>"

What happened to the <tr>?

Batman
  • 5,563
  • 18
  • 79
  • 155
  • 1
    `.html()` retrieves the _inner_ HTML, not the outer HTML. Why do you need to get the outer HTML? – Sebastian Simon Aug 28 '18 at 01:50
  • Possible duplicate of [jQuery: outer html()](https://stackoverflow.com/questions/5744207/jquery-outer-html) – Sebastian Simon Aug 28 '18 at 01:50
  • In case you *really* want the outer HTML you should replace `.html()` with `[0].outerHTML`. This will get the outerHTML property of the first created DOM element of your jQuery object. – Carsten Massmann Aug 28 '18 at 05:09

2 Answers2

0

try this code: HTML:

<table class="parent"></table>

JS:

$('.parent').html('<tr class="name"><td>anything</td></tr>');

if you do not want to replace use this to add:

$('.parent').append('<tr class="name"><td>anything</td></tr>');
0

When chaining it with html() method at the end, it only returns outer HTML for the <tr>. You have not assigned <tr> to any of variable & nor you have added it to DOM yet, hence it is no longer accessible. You have lost it in the local scope.
If you use a variable such that

var $tr = $("<tr>",{class: "ertert"});
$tr.append($("<td>",{text:"adfsadfasdf"})).html()

You will be able to access it again.

Aditya Sharma
  • 645
  • 1
  • 10
  • 28