pee2pee
pee2pee

Reputation: 3802

jQuery Get Specific Content From External Page

So I have something like

<ul>
<li> <a href="123.html">123</a></li>
<li> <a href="abc.html">abc</a></li>
</ul>

This sites in my INDEX.HTML file. Except there are loads more lists and list items. Each HTML page that is linked to has a section like this:

<ul>
<li><strong>Time: </strong>12:00</li>
</ul>

What I want is when the user sees the INDEX.HTML page, the time gets added to the end (from the relative link) so it reads like

Can someone please help? I realise I might need contents() and fine() but have got nowhere quick. So basically for each link, we go to the URL in question, grab the time and add it the original line on INDEX.HTML

Thanks.

Upvotes: 0

Views: 1607

Answers (2)

Erick Petrucelli
Erick Petrucelli

Reputation: 14902

If I understood your problem, I believe you want to load the contents of each inner page to display the information in the main menu. If this is the case, it is a bad idea for performance.

If you want even so, you will first need to load the HTML content using the $.get function. Then work with the result, searching for the desired element.

UPDATE

I updated the sample here. It has only one link, but now showing it with your code structure.

Based on it, I believe your index.html code will be something like this:

$("li a").each(function() {
    var src = $(this).attr("href");
    $.get(src, function(data) {
      var element = $("<div>").html(data);
      var time = element.find("li").contents().last().text();
      $("li").append(" - " + time);
    });
});

Upvotes: 2

pimvdb
pimvdb

Reputation: 154908

The idea could be as follows:

  1. Loop through the lis.
  2. Get the href attribute of the a child.
  3. Send an ajax request to that page.
  4. Parse the response and find the appropriate text using jQuery.
  5. Append that text to the li.

On jsFiddle it's not very easy to generate separate pages, so you'll have to alter it a bit for your case. Also, you may want to make the selector stricter (ul strong is the best I can make up with your example).

http://jsfiddle.net/3JQDz/

$("li").each(function() {
    var $li = $(this);
    var href = $li.find("a").attr("href");  // use this in your real case

    $.ajax({
        type: "POST",
        url: "/echo/html/",  // this is just the way to use ajax on jsFiddle
        data: {
            html: "<ul><li><strong>Time: </strong>12:00</li></ul>"
        },
        success: function(html) {
            // full document -> only the li -> its child nodes -> the last one (the text node) -> its text
            var time = $(html).find("li").contents().last().text();
            $li.append(" - " + time);
        }
    });
});

Upvotes: 2

Related Questions