Skip to content
Advertisement

getSelection().focusNode inside a specific id doesn’t work

I have code to bold/unbold scripts via Window.getSelection() I got it from this answer: Bold/unbold selected text using Window.getSelection()

It really works without problems . But when I looked for another code to make the selection inside a div specified with id I found this answer : How to getSelection() within a specific div? When I try to combine the first answer with the second answer I found it doing bold and not unbold My Code :

function addBold(){

/*
answer 1 
https://stackoverflow.com/questions/63364212/bold-unbold-selected-text-using-window-getselection

answer 2 
https://stackoverflow.com/questions/38758713/how-to-getselection-within-a-specific-div


*/




// answer 2 
if(window.getSelection().baseNode.parentNode.id != "editor") return;
// end answer 2 



// answer 1 
  const selection = window.getSelection().getRangeAt(0);
  
  let selectedParent = selection.commonAncestorContainer.parentElement;
  

  let mainParent = selectedParent;
  
  if(selectedParent.closest("b"))
  {
  //Unbold
    var text = document.createTextNode(selectedParent.textContent);
    mainParent = selectedParent.parentElement;
    mainParent.insertBefore(text, selectedParent);
    mainParent.removeChild(selectedParent);
    mainParent.normalize();
  }
  else
  {
    const span = document.createElement("b");
    span.appendChild(selection.extractContents());
    selection.insertNode(span);
    mainParent.normalize();
  }
  
  //selection is set to body after clicking button for some reason
  //https://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript
  if (window.getSelection) {
    if (window.getSelection().empty) {  // Chrome
      window.getSelection().empty();
    } else if (window.getSelection().removeAllRanges) {  // Firefox
      window.getSelection().removeAllRanges();
    }
  } else if (document.selection) {  // IE?
    document.selection.empty();
  }

// end answer 1



};
<div id="editor" contenteditable="true">

You are the programmers of the future 

</div>


<button onclick="addBold()">Bold</button>

Like I said when you combined the two an swers Makes bold and ignores unbold

If you delete the first line of the validation condition, if(window.getSelection().baseNode.parentNode.id It will work successfully Bold/Unbold

Advertisement

Answer

that window.getSelection().baseNode.parentNode.id When creating bold

The parent element of the text is obtained and find it Text Therefore, he did not reach the main father element who kissed him So replace the first line with this line and it works successfully Replace

window.getSelection().baseNode.parentNode.id != “editor”

To

window.getSelection().focusNode.parentElement.closest(“#editor”).id != “editor”

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement