简体   繁体   中英

Can i link to an element in the dom

I have a static web page consisting of text, broken up into sections with <h2> tags. I don't have access to the underlying code, but I'd like to link to a specific <h2> tag. If I had access to the code I could either mark the tags up with IDs for example: <p id="section1"> - but that's not an option. I could also access them using the DOM index eg document.getElementsByTagName("h2")[0] - so my question really is, is there any way of adding that to a link without needing the associated javascript?

Thanks

Ali

No, you can't do that with just a link.

In one way or the other you need access to the underlaying markup, to either scroll to a position or do a live update of the DOM.

If you can get access to it using an iframe and CORS is not blocking, it could be done that way.

Another way could be to use a server side language, like ASP.NET, from where you read the page, process it and then forward it to the client. This can still backfire depending on how scripts etc. will act on the page in question.

<iframe id="myframe" src="/yourDocument.html" />
var x = document.getElementById("myframe");
var y = (x.contentWindow || x.contentDocument);
if (y.document)y = y.document;
var contLinks = y.body;

as explained here: IFrame contentDocument Property

If you can open the document on an iframe like so or get it's content from a server side script, run this on the returned DOM:

var createLinks = function(){
    var contLinks = document.getElementsByTagName("body");
    for(i=0; i<contLinks.length; i++)
        {
            var Links = document.getElementsByTagName("h2");
            var appendLinks = "";
            for(idx=0; idx<Links.length; idx++)
                {
                    appendLinks += "<a href='"+Links[idx].innerHTML.trim()+"'>"+Links[idx].innerHTML.trim()+"</a><br/>";
                    //Links[idx].remove;
                }
            contLinks[i].innerHTML = appendLinks;
        }
  }
 createLinks();

Direct the last line contLinks[i].innerHTML = appendLinks; to the output that you prefer...

If you definitely can't use any kind of interaction with the document, then you just can't use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM