admin管理员组

文章数量:1334148

I use this:

function setFontSize() {
   var p = document.getElementsByTagName('td');
   for(i=0;i<p.length;i++) {
      p[i].style.fontSize = selectedsize+"px"
   }
}

What's the simplest and best way to throw in 'th' too?

I use this:

function setFontSize() {
   var p = document.getElementsByTagName('td');
   for(i=0;i<p.length;i++) {
      p[i].style.fontSize = selectedsize+"px"
   }
}

What's the simplest and best way to throw in 'th' too?

Share Improve this question asked May 26, 2013 at 12:42 Ole SørensenOle Sørensen 3595 silver badges19 bronze badges 6
  • 6 querySelectorAll – elclanrs Commented May 26, 2013 at 12:45
  • Why not add a class on the <table> element, and then #table.big-fonts td { font-size: 125% } stuff. Querying all the cells manually and writing their style is not a good approach. – Šime Vidas Commented May 26, 2013 at 13:33
  • @elclanrs Think outside of the box. Why walk the DOM to find all cells when you can just set a class name on the table? – Šime Vidas Commented May 26, 2013 at 13:34
  • I didn't know about querySelectorAll. Reading up on that now. Thanks. – Ole Sørensen Commented May 26, 2013 at 19:32
  • With my limited insight I would just love to not batch through my whole site to add a class to the tables that I consider default styled tables. – Ole Sørensen Commented May 26, 2013 at 19:35
 |  Show 1 more ment

2 Answers 2

Reset to default 10

If you don't have to support older browsers you can use document.querySelectorAll(..).

function setFontSize() {
   var i;
   var p = document.querySelectorAll('td, tr');
   for( i = 0; i < p.length; i++ ) {
      p[i].style.fontSize = selectedsize + "px"
   }
}
function setFontSize() {
   var p = document.getElementsByTagName('td'),
       ths = document.getElementsByTagName('th'),
       val = selectedsize + "px";
   for(var i = 0; i < p.length; i++) {
      p[i].style.fontSize = val;
      ths[i].style.fontSize = val;
   }
}

本文标签: javascriptgetElementsByTagName for two tags at onceStack Overflow