Search code examples
javascriptjqueryhtmlfirefoxgetelementbyid

Use getElementById() on non-current HTML document


Essentially, I want to pull text within a div tag from a document on my server to place it in the current document. To explain the reason: I want to pull a headline from a "news article" to use it as the text for a link to that article.

For example, within the target HTML is the tag:

<div id='news-header'>Big Day in Wonderland</div>

So in my current document I want to use javascript to set the text within my anchor tags to that headline, i.e.:

<a href='index.php?link=to_page'>Big Day in Wonderland</a>

I'm having trouble figuring out how to access the non-current document in JS.

Thanks in advance for your help.

ADDED: Firefox style issue (see comment below).


Solution

  • Normally, I would try to solve an issue only with the tools specified by the user; but if you are using javascript, there really is no good reason not to just use jQuery.

    <a id='mylink' href='url_of_new_article' linked_div='id_of_title'></a>
    
    $(function() {
        var a = $('#mylink');
        a.load(a.attr('href') + ' #' + a.attr('linked_div'));
    });
    

    That little function up there can help you update all your link's text dynamically. If you have more than one, you can just put it in a $('a').each() loop and call it a day.

    update to support multiple links on condition:

    $(function() {
        $('a[linked_div]').each(function() {
            var a = $(this);
            a.load(a.attr('href') + ' #' + a.attr('linked_div'));
         });
    });
    

    The selector makes sure that only the links with the existence of the attribute 'linked_div' will be processed.