JSFiddle - React, Tailwind, and code Playground

HTML

Hello

<p id='p'>Select me</p>


World

<button id ='btn'>Select text</button>

JavaScript

document.getElementById('btn').addEventListener('click', function(){
    var range = document.createRange();
    var selection = window.getSelection();
    range.selectNodeContents(document.getElementById('p'));
    
    selection.removeAllRanges();
    selection.addRange(range);
});