Change a string of two html files from javaScript

I have a list in one file html called "filed1":

<ul> 
    <li>Nombre:<a class="boton" onclick=move() title="Caja">Caja</a><br> 
    <FONT SIZE=2>Fecha: 21/12/1994</font></font></li>
</ul>

Now I want to change a string in other html "filed2":

<a id="logo-header2">
    <h1>
        <span class="site-name" id="element">Details</span><br>
    </h1>
</a> 

Using Java Script:

function move() {
    mywindow = window.open("file2.html");
    mywindow.document.getElementById("element").innerHTML="Changed");
}

But there is an error which says that mywindow.document.getElementById("element") is NULL, why? The id element exists in the other window. Is there another way to change the string?

Answers


The problem is that you are trying to retrieve the DOM element before the window is loaded.

Try following

mywindow.onload = function() {
    mywindow.document.getElementById("element").innerHTML="Changed";
}

Like @nikhil mentioned, mywindow is undefined when you're calling it, and you'll need to place your code into something triggered by the onload event.

Another approach you can try is perhaps passing the string as a variable in the url, like so:

function move(){
    window.open("file2.html?str=Changed");
}

And then in file2.html, try something that runs on page load:

window.onload = function(){
    var str = $_GET('str');
    document.getElementById("element").innerHTML = str;
};

function $_GET(q){
    var $_GET = {};
    if(document.location.toString().indexOf('?') !== -1){
        var query = document.location
                       .toString()
                       .replace(/^.*?\?/, '')//Get the query string
                       .replace(/#.*$/, '')//and remove any existing hash string
                       .split('&');
        for(var i=0, l=query.length; i<l; i++){
           var aux = decodeURIComponent(query[i]).split('=');
           $_GET[aux[0]] = aux[1];
        }
    }
    return $_GET[q];
}

The $_GET function I included is just for getting query string parameters, and function much like $_GET[] in php.


Need Your Help

Progress bar for loading out another JFrame class

java swing progress-bar listener

I have 2 JFrame: NewJFrame and NewJFrame1. NewJFrame has a progress bar and a button. the button is used to call up NewJFrame1. When the button is clicked it should trigger the progress bar to run...

Xcode 7: Linker warning for -F/<path> but no settings in app.xcodeproj/project.pbxproj match <path>

ios xcode

I converted a Swift 1.x project for iOS to Swift 2.x using Xcode 7 beta 3. It compiles and runs but I have a linker warning persisting. I've done a search through the project.pbxprox for the offe...