admin管理员组

文章数量:1291239

My first question here.

Given a table:

<table id="mytable">
 <tr><td>row1 col1</td><td>row1 col2</td></tr>
 <tr><td>row2 col1</td><td>row2 col2</td></tr>
</table>

I know that if I were to wrap the above with <div style="overflow-x:scroll;"> , I will have a horizontal scrollbar underneath the table. Unfortunately, I can't alter the way the table / html is written. I can only manipulate the contents via javascript.

I tried:

document.getElementByID("mytable").style.overflowX = scroll;

but it didn't work.

Any idea if it can be done? How?

Thanks in advance.

My first question here.

Given a table:

<table id="mytable">
 <tr><td>row1 col1</td><td>row1 col2</td></tr>
 <tr><td>row2 col1</td><td>row2 col2</td></tr>
</table>

I know that if I were to wrap the above with <div style="overflow-x:scroll;"> , I will have a horizontal scrollbar underneath the table. Unfortunately, I can't alter the way the table / html is written. I can only manipulate the contents via javascript.

I tried:

document.getElementByID("mytable").style.overflowX = scroll;

but it didn't work.

Any idea if it can be done? How?

Thanks in advance.

Share Improve this question asked Apr 4, 2013 at 11:00 Jax SantiagoJax Santiago 131 silver badge3 bronze badges 3
  • please be more specific! what is your aim? you want to scroll your data? or something? you have not specified that. – Patriks Commented Apr 4, 2013 at 11:06
  • Jax, did you get it done? if yes mark answer as right to set question as resolved, and if not, then ment what is progress please. – Patriks Commented Apr 4, 2013 at 12:26
  • Yes. I wanted to have horizontal scrolling capability on the system generated table. I did try the code you gave below. Worked like a charm. thank you very much! – Jax Santiago Commented Apr 4, 2013 at 12:54
Add a ment  | 

2 Answers 2

Reset to default 8

You can use

$("#yorutable").wrap($("<div />").css("overflow-x":"scroll"));

to warp your table with a div run time.

If you can not add jquery, you can do something like

var tbl = document.getElementById('yourtable'); 
var parent = tbl.parentNode;
var wrapper = document.createElement('div');
wrapper.style.overflowX="scroll"; 
wrapper.appendChild(tbl);
parent.appendChild(wrapper);

Pratik's solution was educational, but not 100% correct. It will work if the table is the last item in its parent; otherwise it reorders the table to be last. This question tells the rest of the story.

Putting the whole story together:

var tbl = document.getElementById('yourtable'); 
var parent = tbl.parentNode;
var wrapper = document.createElement('div');
wrapper.style.overflowX="scroll"; 
parent.insertBefore( wrapper, tbl );
wrapper.appendChild(tbl);

本文标签: javascriptWrap Table with DIV at runtimeStack Overflow