I am writing a script that needs to add DOM elements to the page, at the place where the script is located (widget-like approach).
What is the best way to do this?
Here are the techniques I am considering:
- Include an element with an id="Locator" right above the script. Issues:
- I don't like the extra markup
- If I reuse the widget in the page, several elements will have the same "Locator" id. I was thinking about adding a line in the script to remove the id once used, but still...
- Add an id to the script. Issues:
- even though it seems to work, the id attribute is not valid for the script element
- same issue as above, several elements will have the same id if I reuse the script in the page.
- Use getElementsByTagName("script") and pick the last element. This has worked for me so far, it just seems a little heavy and I am not sure if it is reliable (thinking about deferred scripts)
document.write: not elegant, but seems to do the job.
[Edit] Based on the reply from idealmachine, I am thinking about one more option:
- Include in the script tag an attribute, for example goal="tabify".
- Use getElementsByTagName("script") to get all the scripts.
- Loop through the scripts and check the goal="tabify" attribute to find my script.
- Remove the goal attribute in case there's another widget in the page.
[Edit] Another idea, also inspired by the replies so far:
- Use getElementsByTagName("script") to get all the scripts.
- Loop through the scripts and check innerHTML to find my script.
- At the end of the script, remove the script tag in case there's another widget in the page.
I just found another method that seems to answer my question:
How to access parent Iframe from javascript
Embedding the script in an iframe allows to locate it anytime, as the script always keeps a reference to its own window.
I vote this the best approach, as it'll always work no matter how many times you add the script to the page (think widget). You're welcome to comment.
What pushed me to consider iframes in the first place was an experiment I did to build a Google gadget.