0

I am trying to link to another page (that I cannot modify). The page, unfortunately, does not have unique names or IDs for each section. Instead, the section headers are simply inside an h2 tag.

For example:

<h2>Section A</h2>
<h2>Section B</h2>
<h2>Section C</h2>
<h2>Section D</h2>
<h2>Section E</h2>
<h2>Section F</h2>
<h2>Section G</h2>
<h2>Section H</h2>
<h2>Section I</h2>
<h2>Section J</h2>

Basically, I want to point my link so that it goes directly to "Section F". However, there are no anchors, so is this even possible to do?

ZeekLTK
  • 233
  • 2
  • 9
  • Possible duplicate of [Is there any way to bookmark or link to a section of a page without an anchor?](http://stackoverflow.com/questions/7983290/is-there-any-way-to-bookmark-or-link-to-a-section-of-a-page-without-an-anchor) – Ryan Oct 05 '15 at 18:07
  • This is definitely possible with JS. Find the h2 tag you want by some means, letter to index in `getElementsByTagName` perhaps, then determine its location on the page and use `window.scrollTo`. – William_Wilson Oct 05 '15 at 18:10
  • @Ryan OP mentioned not even `id`'s. – divy3993 Oct 05 '15 at 18:11
  • If you are able to use javascript to manipulate the page, such as access to the target page loaded into an iFrame, then yes, you can. Otherwise there's not much you can do against an external page. – Kal_Torak Oct 05 '15 at 18:18

1 Answers1

0

use getPos from Get the position of a div/span tag.

Call with goTo( "Section C" ); for example.

function goTo( text )
{
    var h2s = document.getElementsByTagName( 'h2' );

    for( var i = 0; i < h2s.length; ++i )
    {
        if( h2s[i].innerHTML.trim() == text.trim() )
        {
            window.scrollTo( h2s[i] );
            return;
        }
    }
}

*Not tested, but should get you close.

Community
  • 1
  • 1
William_Wilson
  • 1,244
  • 7
  • 16