Niko
Niko

Reputation: 251

How can I link directly to a div that has been generated by innerHTML?

So I started out using innerHTML when I wanted to generate a series of divs similar to the following.

<div id="123233"></div>
<div id="123234"></div>
<div id="123235"></div>

Now I have realized that I want to link directly to these divs.

For example: www.example.com/page#123234

I have discovered a few scenarios.

  1. If I go directly to www.example.com/page#123234 it behaves as if #123234 wasn't there.
  2. If I first go to www.example.com/page and then adds #123234 in the url it works as desired.
  3. If I go www.example.com/page#123234 and then write in the same url again it doesn't work.
  4. If I perform scenario 2 and then reloads the page it stays in the same position.
  5. If I perform scenario 2 and write in the same url again it doesn't work.

So with this in mind I have my question...

How can I link directly to a div that has been generated by innerHTML?

Additional Information:

I would like the link to work from everywhere. Could be an external domain or just another page like www.example.com/startpage.

Upvotes: 1

Views: 154

Answers (2)

Jose Faeti
Jose Faeti

Reputation: 12302

Since you are assigning an ID to each element, you could find the element by its ID once they are created, and after getting it from the query string, and scroll the page down to its location.

I would suggest creating the elements with javascript commands rather than with innerHTML, as you already have a reference to them this way.

Also, as far as I know IDs should start with a letter as for the HTML specs.

Upvotes: 1

Nathan
Nathan

Reputation: 11149

In your JavaScript, you must be either using some kind of onload or putting all the scripting at the end so that you can use innerHTML. I'll assume the former. So you have:

window.onload = function () {
    document.body.innerHTML += "<div id="123233"></div>";
};

If you add a line to refresh the hash (the bit after the #), then it should scroll to the place you expect:

window.onload = function () {
    document.body.innerHTML += "<div id=\"123233\"></div>";
    window.location.hash = window.location.hash;
};

All that is doing is setting the hash to what it is already set to, but the difference being that it is a valid hash when it is set, whereas it isn't when the page first loads.

Upvotes: 1

Related Questions