Samra
Samra

Reputation: 2015

add a div inside a td jquery

I want to add a div inside a td.

My td before

<td>Fiction</td>

After i write code

var cell =  getCell(indexRow + 1, colIndex);
var wrap = $('<div/>').attr('id', 'container');

cell.append(wrap);

Now it becomes

<td> Fiction [object Object] </td>

javascript

function getCell(row, col){

    var currentRow = $('#MapDetails tr')[row];
    var cell = $(currentRow).find('td')[col];

    return cell;
}

Upvotes: 1

Views: 4784

Answers (4)

Debasis Panda
Debasis Panda

Reputation: 463

<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
      $(function() {
        var indexRow = 0;
        var colIndex = 0;
        var cell = getCell(indexRow + 1, colIndex),
          $cell = $(cell);
        var wrap = $('<div/>').attr('id', 'container').text($cell.text());

        $cell.html(wrap);

        function getCell(row, col) {
          var currentRow = $('#MapDetails tr')[row];
          var cell = $(currentRow).find('td')[col];

          return cell;
        }
      });

    </script>
  </head>

  <body>
    <table id="MapDetails">
      <tr>
        <th>name</th>
        <th>title</th>
      </tr>
      <tr>
        <td>Samra</td>
        <td>Developer</td>
      </tr>
      <tr>
        <td>Debasis</td>
        <td>Developer</td>
      </tr>
    </table>
  </body>

</html>

Upvotes: 0

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

There was a couple syntax errors.

Look this code and feel free to ask questions...

function getCell(row, col){

  var currentRow = $('#MapDetails tr');
  var cell = currentRow.eq(row).find('td').eq(col);

  return cell;
}

var indexRow = 0;
var colIndex = 0;

var cell =  getCell(indexRow + 1, colIndex);
var wrap = $('<div>').attr('id', 'container').text("I'm the new div!");
cell.append(wrap);
td{
  border:1px solid black;
}
td div{
  border: 2px solid red;
  padding: 4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="MapDetails">
  <tr>
    <th>Header</th>
  </tr>
  <tr>
    <td>Fiction</td>
  </tr>
</table>

Upvotes: 3

Lee Han Kyeol
Lee Han Kyeol

Reputation: 2481

.attr(key, value) only sets the attributes to the jQuery object.

You might want to create one with the specific attributes by following code.

var cell =  getCell(indexRow + 1, colIndex);
var wrap = $('<div />', {id: 'container'});

cell.append(wrap);

Or If you want wrap to be the only element inside <td> then

cell.html(wrap);

Upvotes: 0

eMaX
eMaX

Reputation: 1

Use hmlt instead of append Hope this will solve using html like this cell.html(""), Let me know if this doesn't work,

Upvotes: 0

Related Questions