<div class="wrapper">
  <p class="text">Here is some text and the last word will be <span id="selectable">selected</span></p>
  
  <button id="button">Highlight Text</button>
</div>
.wrapper {
  border: 3px solid #121212;
  height: 60vh;
  padding: 20px;
}

.text {
  font-family: "Arial";
  font-size: 1.4rem;
}

#button {
  background-color: rgb(255, 65, 99);
  border: 2px solid #121212;
  cursor: pointer;
  padding: 10px 15px;
}
const highlightText = (element) => {
    if (document.body.createTextRange) {
        const range = document.body.createTextRange();
      
        range.moveToElementText(element);
        range.select();
    } else if (window.getSelection) {
        const selection = window.getSelection();
        const range = document.createRange();
      
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
    } else {
        alert("Highlighting text is not supported in this browser.");
    }
}

const element = document.getElementById("selectable");

document.getElementById("button").addEventListener("click", () => highlightText(element));

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.