user475685
user475685

Reputation: 8319

problem using window.location

I have an html page:

<html>
<head>
<script type="text/javascript">
function myfunct()
{
window.location='test.html';
document.getElementById("message")="hello";
}
</script>
</head>
<body>
<input type="button" value="click" onclick="myfunct()"/>
</body>
</html>

test.html:

<html><head></head>
<body>
<div id="message">Some text</div>
</body>
</html>

The problem is that window.location is working fine but the div is not getting updated to "hello".

Upvotes: 0

Views: 3370

Answers (4)

Guffa
Guffa

Reputation: 700322

You can't assign a string to an element, you have to use the innerHTML property. Also, as the element is in the page that you open, you have to have the code in that page instead.

test.html:

<html>
<head>
<script type="text/javascript">

window.onload = function() {
  document.getElementById("message").innerHTML = "hello";
}

</script>

</head>
<body>
<div id="message">Some text</div>
</body>
</html>

If you want to send the message along from the first page, you have to send it as data to the new page, so that it can display it:

In the first page:

window.location.href = 'test.html?hello';

In test.html:

window.onload = function() {
  document.getElementById("message").innerHTML = window.location.search.substr(1);
}

Upvotes: 2

Slappy
Slappy

Reputation: 4092

The element you are trying to set to 'Hello World' does not exist on the page you're function is on. You can only access elements on your current page. When a page refresh happens it recreates the HTML DOM from the requested page. You cannot access another pages DOM directly.

Upvotes: 1

Bhoomi
Bhoomi

Reputation: 80

you have to write in test.htm

document.getElementById("message")="hello";

not in your html

Upvotes: 1

Kishan Gajjar
Kishan Gajjar

Reputation: 1138

you have to write

function myfunct() { document.getElementById("message")="hello"; }

in test.html page...

and call this function on page Load event of test.html

Upvotes: 1

Related Questions