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.

3
  • 1
    Possible duplicate of Get another page's content in a variable with ajax Commented Jul 18, 2016 at 21:20
  • Look into forms and posting. Then look into jQuery .post() or AJAX methods. These should help you get started ... Commented Jul 18, 2016 at 21:21
  • 1
    If one of the pages is in an iframe, you can directly access its elements from the other page. Commented May 27, 2022 at 18:31

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.