3

How to load divs from page 2 into page 1 with JavaScript.

Page2.html

<html>
<head>
<title> title </title>
<body>
<div id="main">
<div id="content2"> this is content2</div>
<div id="content3"> this is content3</div>
</div>
</body>
</html>

I want to get and use the id content2 from page2 to create a div into page1 with the content of that div, after link was clicked and deleted, and do the same with content3, content4 and successively.

Page1.html

<html>
<head>
<title> title </title>
<body>
<div id="main">
<div id="content1"> this is content1</div>
<a href="#"> get content</a>
</div>
</body>
</html>

And then would be like that.

<html>
<head>
<title> title </title>
<body>
<div id="main">
<div id="content1"> this is content1</div>
<div>this is content2</div>
<div>this is content3</div>
</div>
</body>
</html>

I'm new in JavaScript and i have no ideia how to do that. If someone can help. Thanks.

Edited: I wanted a way to do it only with javascript and without jquery if that's really possible. I want my project working offline and I can't do that with jquery, because it doesn't work. I've downloaded jquery plugin and pasted it in my directory, but, didn't work, too.

EL S
  • 92
  • 1
  • 1
  • 12
  • 1
    Possible duplicate of [Get another page's content in a variable with ajax](http://stackoverflow.com/questions/20927573/get-another-pages-content-in-a-variable-with-ajax) – Heretic Monkey Jul 18 '16 at 21:20
  • Look into forms and posting. Then look into jQuery `.post()` or `AJAX` methods. These should help you get started ... – Zak Jul 18 '16 at 21:21
  • 1
    If one of the pages is in an iframe, you can directly [access its elements](https://stackoverflow.com/questions/1451208/access-iframe-elements-in-javascript) from the other page. – Anderson Green May 27 '22 at 18:31

2 Answers2

4

You can use a combination of JavaScript, jQuery, and AJAX to accomplish this.

First, include the jQuery library:

<script src="//code.jquery.com/jquery-1.10.2.js"></script>

Then write a JavaScript function similar to this one which will replace your div element's html content with the Page2.html file:

var loadNewContent = function {
  $.ajax("Page2.html", {
    success: function(response) {
      $("#content2").html(response);
    }
  }); 
};

And then you would need some 'trigger' to run this function such as this:

$("#content2").on('click', loadNewContent);

Hope this helps.

awran5
  • 4,333
  • 2
  • 15
  • 32
b0rgBart3
  • 304
  • 1
  • 5
0

I wrote a small library called ViaJS using javascript & jquery. It basically lets you load content (like a div) from a source to the page. Check it out.

Via is a small library that allows you to load content on to a page dynamically

Abdullahi
  • 134
  • 8