Javascript DOM CSS Style userSelect Property

Introduction

Prevent text selection of a <div> element:

document.getElementById("myDiv").style.userSelect = "none";

Click the button to set the user-select property of the p element to "none":

View in separate window

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Test</button>

<p id="demo">After you click on the button, it is not possible to select the text of this p element.</p>

<script>
function myFunction() {/*from  ww w.  j  av  a  2 s.  c  om*/
  var x = document.getElementById("demo");
  x.style.WebkitUserSelect = "none"; // Safari
  x.style.msUserSelect = "none"; // IE 10+ and Edge
  x.style.userSelect = "none"; // Standard syntax
}
</script>

</body>
</html>

The userSelect property sets or gets whether the text of an element can be selected.

Property Values

Parameter Description
auto Default. Text can be selected according to the browser's default settings
none Prevent text selection
text The text can be selected by the user
all Text selection is made with one click instead of a double-click

The userSelect property returns a String representing whether the text of an element can be selected.




PreviousNext

Related