Stefan Hesman
Stefan Hesman

Reputation: 31

How can I change height of a Table element with JavaScript?

I can change bgcolor and width but not height. What's the problem?

function change() {
  document.getElementById('tabelID').bgColor = 'green';
  document.getElementById('tabelID').height = 50;
  document.getElementById('tabelID').width = 100;
}
<button onclick='change();'>change now</button>
<table id='tabelID' bgcolor='red' height='20' width='20'></table>

Upvotes: 1

Views: 2826

Answers (3)

Barmar
Barmar

Reputation: 782653

Properties and attributes don't always have the same names.

The height attribute corresponds to the clientHeight property, but this is a read-only property. Use setAttribute() to change the attribute.

But as I mentioned in a comment, it would be better to use CSS than the obsolete attributes.

function change() {
  document.getElementById('tabelID').bgColor = 'green';
  document.getElementById('tabelID').setAttribute("height", 50);
  document.getElementById('tabelID').setAttribute("width", 100);
}
<button onclick='change();'>change now</button>
<table id='tabelID' bgcolor='red' height='20' width='20'></table>

Upvotes: 1

pretzelhammer
pretzelhammer

Reputation: 15165

The bgcolor, width, and height attributes on table have been deprecated. You should use the CSS properties background-color, width, and height instead. Here's an updated example that changes the table by toggling a CSS class:

function toggleChanges() {
    document.getElementById('tabelID').classList.toggle('larger');
}
.mytable {
    background-color: red;
    width: 50px;
    height: 50px;
}

.mytable.larger {
    background-color: green;
    width: 100px;
    height: 100px;
}
<button onclick='toggleChanges();'>toggle changes</button>
<table id='tabelID' class='mytable'></table>

Upvotes: 2

Fran Perej&#243;n
Fran Perej&#243;n

Reputation: 101

I will let you this code running, you need to use css, and for height and width define a metric (px, %, ...), maybe that could help you!

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<button onclick='change();'>change now</button>
<table style="background-color:red ;height:20px ;width:20px;" id='tabelID' ></table>

<script type='text/javascript'>
function change() {
   document.getElementById('tabelID').style.backgroundColor = 'green';
   document.getElementById('tabelID').style.height = "50px";
   document.getElementById('tabelID').style.width = "100px";
}
</script>
</body>
</html>

Upvotes: 1

Related Questions