Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select an <img> element programmatically using JavaScript?

I have an <img> in an HTML document that I would like to highlight as though the user had highlighted it using the mouse. Is there a way to do that using JavaScript?

I only need it to work in Mozilla, but any and all information is welcome.

EDIT: The reason I want to select the image is actually not so that it appears highlighted, but so that I can then copy the selected image to the clipboard using XPCOM. So the img actually has to be selected for this to work.

like image 365
Joel Anair Avatar asked Sep 24 '08 01:09

Joel Anair


2 Answers

Here's an example which selects the first image on the page (which will be the Stack Overflow logo if you test it out on this page in Firebug):

var s = window.getSelection()
var r = document.createRange();
r.selectNode(document.images[0]);
s.addRange(r)

Relevant documentation:

  • http://developer.mozilla.org/en/DOM/window.getSelection
  • http://developer.mozilla.org/en/DOM/range.selectNode
  • http://developer.mozilla.org/en/DOM/Selection/addRange
like image 57
Jonny Buchanan Avatar answered Nov 14 '22 00:11

Jonny Buchanan


You might also want to call s.removeAllRanges() before s.addRange(r).

like image 1
Neil Avatar answered Nov 14 '22 00:11

Neil