jQuery ignoring initial html element created when calling html()
jQuery ignoring initial html element created when calling html()
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>?
<tr>
.html()
Possible duplicate of jQuery: outer html()
– Xufox
Aug 28 at 1: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.– cars10m
Aug 28 at 5:09
.html()
[0].outerHTML
2 Answers
2
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>');
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
html()
<tr>
<tr>
var $tr = $("<tr>",class: "ertert");
$tr.append($("<td>",text:"adfsadfasdf")).html()
You will be able to access it again.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
.html()retrieves the inner HTML, not the outer HTML. Why do you need to get the outer HTML?– Xufox
Aug 28 at 1:50