First off, get/setAttribute isn't the proper way to do everything and in general should only be resorted to when getting/setting the property isn't working. There are cases though where neither work as expected/desired.
Now, this can only work because form element values are a special case in HTML. No other type of element property can be expected to survive a refresh. Because we are relying upon that for something like this, it's best to access them as part of the the document's forms collection and as part of the form's elements collection. In any case, yes your version - though it accomplishes the same things in the DOM as the below, does not work, while the below code does:
Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
// in head
function checkRefresh() {
var vis = document.forms.hiddenform.elements.visited;
alert("BEFORE: value = " + vis.value);
if (!vis.value){
vis.value = "refreshed";
}
alert("AFTER: value = " + vis.value);
}
</script>
</head>
<body onload="checkRefresh();">
...
<form id="hiddenform">
<input type="hidden" id="visited" name="visited" value="" />
</form>
</body>
</html>
The difference being that because the above code directly accesses the input's value property, it not only changes the DOM, but also the forms collection.
Put another way, you want to access and change the value property, which will also affect the value attribute, not access and change the value attribute which has no effect upon the value property.
This would also work:
Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
// in head
function checkRefresh() {
var vis = document.getElementById('visited');
alert("BEFORE: value = " + vis.value);
if (!vis.value){
vis.value = "refreshed";
}
alert("AFTER: value = " + vis.value);
}
</script>
</head>
<body onload="checkRefresh();">
...
<form id="hiddenform">
<input type="hidden" id="visited" name="visited" value="" />
</form>
</body>
</html>
because it's still accessing the value property as opposed to the value attribute. But it will fail in antiquated 'version 4' browsers.
Bookmarks