'How to setAttribute in cell td HTML?

this is my script but it doesn't work:

var first = document.getElementById("sheet").rows[0];
var two = first.cells(4);
two.setAttribute('style','display:none');


Solution 1:[1]

I dont know if youre really trying to set attribute OR add function onBlur - I will answer both

If you want to set an ATTRIBUTE:

Then your approach is actually right - considering two is a HTMLObject

two.setAttribute("class","unchecked"); //this sets class .unchecked to the "two"

This replaces all existing classes with the new class, fine if you only ever use just 1 class.

Historically you'd have work your own class merging, but for modern browsers, there is much more convenient way: two.classList.add("unchecked"); which adds to existing class list instead of replacing it, but only if the class is not there yet :-)

If you want to add a FUNCTION() which would fire onBlur

Then you have to use something to bind - the easiest way is to add a function inside an HTMLObject attribute(property) - notice! HTMLObject attribute (property) IS NOT the same as attribute you see inside your html code:

two.onblur=function(){  /*SomeJavaScriptCode*/ };

or if you already have a function:

two.onblur = cekUndo;

  • NOTICE! there are no () brackets - the onblur will run the function when its needed you dont want the function to fire immediatly...
  • I recommend you also to check a .addEventListener method - it is more adjustable and you can add e.g. more functions on one event

Note: You can do <td onblur="myFunction()"> - add it directly to HTML, but I dont think you can do that on the run like this you have to bind :) ...

EDIT: as to your second problem - as RobG said, you have to access the cells collection with [] brackets:

var two = first.cells[4];

Also check if you are actually have a cell of that index
(cells are indexed from 0 to X => index 4 means 5th )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1