BLNK
BLNK

Reputation: 154

JQuery, add table row without declaring the tags in Javascript

I wanted to prepare a table row as a template in a HTML doc in order for not typing it in JS as what I've done mostly. I just saved the DOM element as JQuery object and cloned but doing it in a element seems it doesn't saved as an object.

I'm avoiding declaring in JS:

var _row = '<tr><td></td></tr>';

Since I wanted to make the element as dynamic by JS rather than declaring it as a string so I'm trying to create a HTML template for a table row.

In HTML:

<tr id='sampleRow'></tr>

In JS:

var _row = $('#sampleRow');

When consoling log the _row will give a result of init rather than an object.

How can I possibly accomplish like this?

In HTML:

<div class='sampleDiv'></div>

In JS:

var _container = $('.sampleDiv').clone();

In which it is an object.

Upvotes: 0

Views: 93

Answers (2)

Alex Thomsen
Alex Thomsen

Reputation: 54

I personally prefer declaring simple objects like that in javascript through jQuery like this

$("<tr />", {  text: 'Table Row txt',
               class: 'some class',
               id: 'elementid'
             }).appendTo("tbody");

If you want to add elements to that tr you can chain it and use append as well which looks like

$("<tr />", {  text: 'Table Row txt',
               class: 'some class',
               id: 'elementid'
             }).append($('<div />', {
               text: 'Some text inside the div',
               class: 'anotherclass'
             })).appendTo("tbody");

Which would make

<tr class='some class' id='elementid'>Table Row txt
  <div class='anotherclass'>Some Text inside the div</div> 
<tr/>

If you want to use html as a template I would instead suggest using a method like John Resig suggests

http://ejohn.org/blog/javascript-micro-templating/

So you can do

<script type='companyname/mytemplate' id='trTemplate'>
 <tr id='sampleRow'></tr>
</script>

var template = $($("#trTemplate").innerHtml());

Upvotes: 0

BLNK
BLNK

Reputation: 154

I just found my solution,

Instead of using as the container for table row template in which when you call it via JQuery and clone it and append to a table nothing happens, I used a table as the container.

In HTML:

<table class="destTable">
</table>

<table class="tableRowTmp" hidden>
    <tr><td colspan="6">Sample</td></tr>
</table>

In JS:

var oBannerTable = $('.destTable');
var oRow = $('.tableRowTmp').find('tr').clone();

oBannerTable.append(oRow.show());

Upvotes: 1

Related Questions