frequently ask ? : Computers : Programming : Languages : JavaScript : DHTML

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

17 of 19 people (89%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How can I select an element when the user clicks it?
How can I select an element when the user clicks it?

Feb 20th, 2001 14:08
Martin Honnen,


IE4+ and Mozilla (at least with current M0.8 so expect that to work in 
later NN6 releases) allow to change the selection, both by manipulating 
so called ranges, though the apis of IE and Mozilla differ strongly.
Here is an example
<HTML>
<HEAD>
<SCRIPT>
function selectElement (element) {
  if (document.selection) {
    var range = document.body.createTextRange();
    range.moveToElementText(element);
    range.select();
  }
  else if (window.getSelection) {
    var range = document.createRange();
    range.selectNodeContents(element);
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
 }
}
</SCRIPT>
</HEAD>
<BODY>
<DIV ONCLICK="selectElement(this)">
Kibology for all.
</DIV>
<DIV ONCLICK="selectElement(this)">
All for Kibology.
</DIV>
</BODY>
</HTML>