I want to create a bookmarklet that insert a html tag after a certain tag in an existing page, in this case the div below. How would you do that?
<div class="links">
<a href="http://example.com">Link</a>
<-- Insert here -->
</div>
You can just use the following:
javascript:document.getElementsByClassName('links')[0].getElementsByTagName('a')[0].outerHTML+='<!-- Insert here -->';
This would simply replace the link's HTML contents with what's already its HTML content, and add the part you want to add behind it.
This script will select only the first link in the first usage of class="links"
on the page. If this doesn't work, there are probably either more elements with class="links"
on that page, or the link you're trying to add to isn't the first. You can change the numbers in [0]
to [1]
to select the second, [2]
for the third, etc.
With jQuery, you could also use:
javascript:$('.links a').after('<!-- Insert here -->');
but that would add the new content to every link inside every element with class="links"
. If you want it to do the same as the native-JS example above (selecting only the first link inside class="links"
), you can use the following:
javascript:$('.links:eq(0) a:eq(0)').after('<!-- Insert here-->');