Question

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>
Était-ce utile?

La solution

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-->');

Autres conseils

In case page has the jQuery loaded you can simply try this:

javascript:jQuery('<-- Insert here -->').insertAfter('.links a');

and a bookmarklet in this case would be:

javascript:(function(){jQuery('<--%20Insert%20here%20-->').insertAfter('.links%20a');})();

If you need to add that to first occurency of the .link > a, add after insertAfter('.links a').eq(0)

.eq(0) means the first element, second would be .eq(1) etc. You can use one of online bookmarklet generator co easily create that, here is one : Bookmarklet Crunchinator

With jQuery it is pretty simple...

javascript:$('.links').append("<a href='http://stackoverflow.com'>stack overflow</a>")

It is simply appending some html to the element with class links.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top