Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using particular word of <p> element in html

<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

like image 990
eliya Avatar asked Dec 05 '14 10:12

eliya


2 Answers

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

like image 56
Denys Séguret Avatar answered Oct 05 '22 21:10

Denys Séguret


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>
like image 37
Rahul Desai Avatar answered Oct 05 '22 20:10

Rahul Desai