开发者

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 s开发者_JAVA百科tyle issue (see comment below).


I'm not sure where you're getting your HTML but, assuming you already have it in a string, you could create a document of your own, stuff your HTML into it, and then use the standard getElementById to pull out the piece you want. For example:

var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
doc.documentElement.innerHTML = '<body><div>Nonsense</div><div id="news-header">Big Day in Wonderland</div><p>pancakes</p></body>';
var h = doc.getElementById('news-header');
// And now use `h` like any other DOM object.

Live version: http://jsfiddle.net/ambiguous/ZZq2z/1/


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.


You need to pull the content of the remote document into the current DOM, as QuentinUK mentioned. I'd recommend something like jQuery's .load() method

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜