'Get element by id from another page by JavaScript

I have 2 pages index.html and about.html. In about.html there's a table aI need to get value from TD with id = 'id1' and assign it to some variable X to be used later at page index.html.

This would perfectly worked if I had it in one page.

var X = document.getElementById('id1').innerHTML;
alert(X); // 123
...
<td id='id1'>123</td>
...
But how to get value from id1 from about.html? I'd prefer JavaScript because I'm not so good with jQuery at the moment, but if it's not possible jQuery would be nice too.


Solution 1:[1]

One way to do what you want is to store the value of x to localStorage like so:

localStorage.setItem('someName', x);

And then access it from yout other page like so (provided that both pages are part of the same domain name):

x = localStorage.getItem('someName', x);

Solution 2:[2]

You can use ajax. With jQuery it will be much easier.

So, based on using jQuery, you can use load function.

index.html

javascript

$('button').click(function() {
  $('<div />').load('/toruta #td1', function(data) {
    alert($(this).find('td').html());
  });
});

html

<button>show</button>

about.html

<table>
  <tr>
    <td id="td1">loaded via ajax</td>
  </tr>
</table>

Working bin

index like: http://output.jsbin.com/pafehe

about like: http://output.jsbin.com/toruta

Solution 3:[3]

You can use window.localStorage:

  localStorage.setItem('x', document.getElementById('id1').innerHTML);

Now on the second page you can get it:

 var x = localStorage.getItem('x');
 if(x){
    alert(x);
 }

You can send it in the url, let's say you are able to create URL like about.HTML?x=thevalue. Then on the about page:

if(location.href.index of('=') !== -1){
    var x = location.href.split('=').pop();
    alert(x);
}

.split() will create array and .pop() will give you the last element of the array which in this case will be 123.

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 Dimitris Karagiannis
Solution 2 Mosh Feu
Solution 3