Question

hello i want i have function to get paragraph of selected text.

this is the function to get current paragraph of selected text

function getSelected() {
  var userSelection;
  if (window.getSelection) {
      selection = window.getSelection();
  } else if (document.selection) {
      selection = document.selection.createRange();
  }
  var parent = selection.anchorNode;
  parent = parent.parentNode;
  alert(parent.innerHTML);

}

how can i get next-previous paragraph of selected text in web page. if i have function to get current paragraph above. (i think to use nextSibling but i don't know to implement it in code above) can you help me?

-thank you-

Was it helpful?

Solution

You can use previousSibling and nextSibling to get parameters.

HTML:

<p> This is 1st paragraph</p>
<p> This is 2nd paragraph</p>
<p> This is 3rd paragraph</p>
<a href="javascript:void(0)" onclick="getSelected(-1)">Prev</a>
<a href="javascript:void(0)" onclick="getSelected(1)">Next</a>

Javascript:

function getSelected(direction) {
  var userSelection;
  if (window.getSelection) {
      selection = window.getSelection();
  } else if (document.selection) {
      selection = document.selection.createRange();
  }
  var parent = selection.anchorNode;
  parent = parent.parentNode;
  if(direction == -1){
    var prevEle = parent.previousSibling;
    while(prevEle.nodeType!=1){
        prevEle = prevEle.previousSibling;
    }
    alert(prevEle.innerHTML);
  }else {
    var nextEle = parent.nextSibling ;
    while(nextEle.nodeType!=1){
        nextEle = nextEle.nextSibling;
    }
    alert(nextEle.innerHTML);
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top