Using the specific word of the <p> element in html
<p> this is a car</p> //HTML p element Is there a way that I can only use the word that I press, for example, if I click on a car, then only "car" is used. if I click on it, then only 'this' is used. that is 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' } ps I need to use only one click. My p element contains no more than 10 words.
Thanks in advance
Assuming your paragraph contains only text, you can use a small script to prepare the paragraph by dividing 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; } }); Easy if you are considering a double click event. For this you need to use the dblclick event in Javascript.
Check out 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> Put the word car in the span element - onclick should go in between. Like this:
<p id="demo">This is a <span id = "demo_car" onclick="myFunction()>car</span></p>