<p> this is a car</p> //HTML p element
Is there any way that I can use the word only that I click on e.g if I click on car only 'car' is used. if I click on this only 'this' is used. i.e. the only word that I click on.
<p id="demo" onclick="myFunction()">This is a car</p>
myFunction() {
var my;
my=document.getElementbyID("demo")[1]; //to get 'is'
}
p.s I need to use only a single word that is clicked. My p element contains at-most 10 words.
Thanks in advance
Assuming your paragraph only contains text, you can use a small script to prepare the paragraph by splitting it into words :
var element = document.getElementById('demo');
element.innerHTML = element.innerHTML.split(' ').map(function(w){
return '<span class=w>'+w+'</span>';
}).join(' ');
[].forEach.call(document.querySelectorAll('.w'), function(w){
w.onclick = function(){
alert(w.innerHTML);
return false;
}
});
Demonstration
Its easy if you consider double click
event instead. You need to use dblclick
event in Javascript to achieve this.
Checkout the code snippet below:
document.getElementById('test').addEventListener('dblclick', function getSelectedText() {
var selectedText = "";
if (window.getSelection) {
selectedText = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
selectedText = document.selection.createRange().text;
}
selectedText = selectedText.trim();
document.getElementById('result').innerHTML = selectedText;
});
<p id="test">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Selected text = <span id="result"></span></p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With