getElementById from another page

吃可爱长大的小学妹 提交于 2019-12-31 01:47:30

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/27930780/getelementbyid-from-another-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!