Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Lauren Waller
Lauren Waller
10,085 Points

Using jQuery, how do I retrieve text from one html page and display it on another?

const $newBlogTitle = $('#newBlogTitle').text();

$('.$columnEnd').append('<br><a href="blogBoilerplate.html">' + $newBlogTitle + '</a>').addClass('text-black-50 font-size-sm');

I have tried this set up a multiple of different ways by changing the element I am trying to retrieve the text from. It only works if I am retrieving text from elements on the same page. Is that the only way it will work? I can't find an answer to my problem anywhere on the internet.

1 Answer

Steven Parker
Steven Parker
220,415 Points

Your JS/jQuery code is loaded from one particular page, and initially that's the only one it has access to. But you can get to other pages (and/or files) by requesting them from the server. The mechanism for doing this is known as AJAX, and there are courses here for that.

jQuery has a particularly easy method to make these requests, .load(). So for example, assuming that the element with ID "#newBlogTitle" is actually inside "blogBoilerplate.html", you could bring it in like this:

$('.$columnEnd').append('<br><a id="AjaxMe" href="blogBoilerplate.html"></a>')
                .addClass('text-black-50 font-size-sm');
$("#AjaxMe").load("blogBoilerplate.html #newBlogTitle");