getElementById from another page
Asked Answered
K

2

5

I am trying to get one div from one webpage URL to another webpage and display in plain text using getElementById without using AJAX or jQuery because I'm going to implement it in FitNesse. Is there a way to pass the URL?

Kava answered 13/1, 2015 at 20:19 Comment(5)
You can do it with AJAX if that other page is in your domain. Otherwise JSONP or simply a line of PHP might help.Ribera
Not without making any external requests like ajaxThames
Is the pages on the same domain? Otherwise, you might run into some nasty CORS-errors (w3.org/TR/cors)Naphthol
yes it is on the same domainKava
Can we get some of your code so that we can help you improve it.Migrant
I
8

You could load the URL in a hidden iframe.

Then use iframe.contentWindow.document.getElementById($id) as outlined here: How to pick element inside iframe using document.getElementById

Something along the lines of:

<iframe src="urlWithinYourDomain.html" style="display:none"></iframe>

Followed by a function something like:

var divElement = document.getElementById('iframeId').contentWindow.document.getElementById('elementIdOnSourcePage');
document.getElementById('targetParentId').appendChild(divElement);

I'm afraid I can't test this at the moment, so there may be syntax errors, but I think it conveys the idea. It's a bit of a dirty approach, but given your constraints it's the best way I can see to do what you're asking.

Irmgardirmina answered 13/1, 2015 at 21:6 Comment(0)
S
1

On page 1.

<div id="dataDiv">1234</div>
<a id="getData" href="">Page2</a>

<script>
var data = document.getElementById('dataDiv').innerHTML;
//This will get the content from the div above with the id of "dataDiv"

document.getElementById("getData").setAttribute("href","page2.html?var="+data);
//This will set the url of the anchor with the id of "getData" with your url and the passing data.
</script>

And on page 2

  function getUrlVars() {
  var vars = {};
  var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
      vars[key] = value;
  });
  return vars;
  }
  var var1 = getUrlVars()["var"];

This will send the content in your div on page one to page two. the result url on page 1 will be page2.html?var=1234

Squint answered 13/1, 2015 at 20:23 Comment(3)
Edited. If your only passing a few numbers, this is a pretty simple way of doing it.Squint
Adam, what you script does is: setting the whole element's HTML inside a link that after you press you'll navigate to some other page and only on that other page you'll than read the ["var"] String Query. That has nothing to do with scraping content (from an Element ID) from an external page.Ribera
Is he not trying to take the content of a div on page one, and pass it to page2? I just tested my code and it does exactly this. Unless i am misunderstanding the question.Squint

© 2022 - 2024 — McMap. All rights reserved.