huuerequer
huuerequer

Reputation: 131

Jquery problem: adding something to a jquery object

I want to add a string at the end of a jquery object. Something like this:

var mytable = $("<table><tbody><tr><td>");
mytable.after("Test</td></tr></tbody></table>");

I tried with that too

mytable += "Test</td></tr></tbody></table>";

Doesn't work either.

Upvotes: 2

Views: 116

Answers (3)

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146640

jQuery cannot create page elements unless you provide full valid HTML. I'm not sure of your exact needs but you should do something on this line:

var mytable = $("<table><tbody><tr><td></td></tr></tbody></table>").find("td").text("Test");

Upvotes: 1

Jonathon Bolster
Jonathon Bolster

Reputation: 15961

jQuery doesn't work that way. When you're dealing with elements in jQuery they are always valid. If it can't validate it, it won't add it. I tried your example and jQuery completed the invalid HTML:

var mytable = $("<table><tbody><tr><td>");    
// mytable is equal to $("<table><tbody><tr><td></td></tr></tbody></table>");

If you're looking to add a new cell to your table, you could select the required element (i.e. the tr) and then use the append method

mytable.find("tr").append("<td>New cell</td>");

Of course, you can add two strings together and put them in a jQuery object as long as they join to make valid HTML

var string1 = "<table><tbody><tr><td>First half and";
    string1 = " second half</td></tr></tbody></table>";

mytable = $(string1 + string2);

Upvotes: 1

Thariama
Thariama

Reputation: 50840

Problem here is that

"<table><tbody><tr><td>" //jQuery will try to create full html elements from what you enter

is not valid html nor is

"Test</td></tr></tbody></table>" // this will never work, cause this tags are closing only and the table might have been already build when the line before gets executed

jQuery might be able to create valid elements from not fully valid html, but this does not work in every case. I suggest you try to work with valid html!!!

Upvotes: 1

Related Questions