I can get selected text on button click event. But i want get it on a element click event.
Here is my code. Thanks advance
function GetSelectedText(){
console.log(getSelection().toString());
}
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Laborum, nam!</p>
<a role="button" id="a" onclick="GetSelectedText()">a element</a>
<button type="button" id="button" onclick="GetSelectedText()">Button</button>
CodePudding user response:
You can achieve this by adding an event to your a tag this way.
function GetSelectedText(){
selectedText = getSelection().toString();
console.log(selectedText);
}
document.getElementById("a").addEventListener("mousedown", function(event) {
event.stopImmediatePropagation();
event.preventDefault();
});
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Laborum, nam!</p>
<a role="button" id="a" onclick="GetSelectedText()">a element</a>
<button type="button" id="button" onclick="GetSelectedText()">Button</button>
CodePudding user response:
function GetSelectedText(){
const element = document.querySelector("#text");
console.log(element.innerHTML);
return element.innerHTML;
}
<p id="text">Lorem ipsum, dolor sit amet consectetur adipisicing elit. Laborum, nam!</p>
<a role="button" id="a" onclick="GetSelectedText()">a element</a>
<button type="button" id="button" onclick="GetSelectedText()">Button</button>