0

So I have a table that includes hidden items. There's a button that a user can press, and it'll wipe all of the table rows. However, I want to save the hidden elements and append them to the new table.

I tried this to do accomplish that:

var hidden_items = $("input[type='hidden']");
var html = "";
for ( var i = 0, l = hidden_items.length; i < l; i++ ) {
    if (hidden_items[i].closest("tbody") !== null) {
         html += hidden_items[i]
   }
}

The reason I'm doing .closest("tbody") is because there are other hidden inputs on the entire page, and I just want to save the ones that are in the table.

When I do this, the content of html turns out to be nothing but this:

"[object HTMLInputElement][object HTMLInputElement][object HTMLInputElement][object HTMLInputElement][object HTMLInputElement][object HTMLInputElement][object HTMLInputElement][object HTMLInputElement][object HTMLInputElement]"

What am I doing wrong? If I do a console.log(hidden_items[i]) then it actually spits out the correct stuff to the console, so why can't it append to the html string properly?

1 Answer 1

2

This is because your element is an HTML element (Not a string), and you're trying to append it to a string. This will try and convert the object to a string, which is simply [object HTMLInputElement].

The reason this works in your console is because it's smart, and understands it's an element, so it links you directly to it in the DOM, and shows you what it's referring to. If you call console.log(hidden_items[i].toString()), you'll see [object HTMLInputElement] instead.

You have 2 options:

#1. Append the HTML text to the html string. This wont copy things like event listeners/hidden items that may not show in the raw HTML:

var hidden_items = $("input[type='hidden']");
var html = "";
for ( var i = 0, l = hidden_items.length; i < l; i++ ) {
    if (hidden_items[i].closest("tbody") !== null) {
         html += hidden_items[i].outerHTML;
   }
}

#2: Create a div/span, or an array of elements, and use jQuerys append() to add them to the DOM:

var hidden_items = $("input[type='hidden']");
var html = [];
for ( var i = 0, l = hidden_items.length; i < l; i++ ) {
    if (hidden_items[i].closest("tbody") !== null) {
         html.push(hidden_items[i]);
   }
}

$('#toplace').append(html);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.