views:

1783

answers:

2

I have an html file that I'd like to open and read from, but I'm not entirely sure how to do that... Basically, it's a fairly large file (big.html), and, in a separate file (titles.html), I have some jquery code that I'd like to use to find certain elements (namely, h2 tags) and get the inner text from those tags and write just that text to titles.html... I'm not sure, particularly, how to open a separate file and read from it, and secondly, I'm not sure if the code below will work when it comes to getting the text within the h2 tags...

$(document).ready(function() {
    $("h2").each(function() {
        var title = $(this).text();
        $("#mydiv").append(title);
    });
});

...

<div id="mydiv"></div>

I'm a bit confused how to do that with jquery... I'm pretty new to the whole thing, so I'm not even sure it's possible...

A: 

One solution would be to "read" in the 2nd document by putting it in a hidden iframe. Then you could access the HTML in that iframe as noted here:

http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/

and do whatever you like with that data.

Erik
+1  A: 

jQuery provides a method $.get which can capture the data from a URL. So to "read" the html/text document, it needs to be accessible through a URL. Once you fetch the HTML contents you should just be able to wrap that markup as a jQuery wrapped set and search it as normal.

Untested, but the general gist of it...

var HTML_FILE_URL = '/whatever/html/file.html';

$(document).ready(function() {
    $.get(HTML_FILE_URL, function(data) {
        var fileDom = $(data);
        fileDom.find('h2').each(function() {
            alert($(this).text());
        });
    });
});
T. Stone
I tried something like this (and then, this) and I just get an error... script stack space quota is exhausted... so, I guess the file is too big?
phpN00b
Wow... how big (bytes) is the file? You might try loading it in pieces with a series (or loop) of statements like the one provided in the example above.
cjstehno