+ 1

Please help me

When I click the change button i want to change the background of selected text on paragraph 1 to yellow colour, how to do that? How to change elm::selection value using js https://code.sololearn.com/Wv35l982ObR1/?ref=app

27th Jun 2022, 7:32 AM
roshan roy
2 Answers
+ 2
I tried to find answer and it look like there are no simple selector for it. Easiest is to use css variable and change them. https://www.w3schools.com/css/css3_variables_javascript.asp https://davidwalsh.name/css-variables-javascript
27th Jun 2022, 9:13 AM
PanicS
PanicS - avatar
+ 1
Search for Selection API -https://developer.mozilla.org/en-US/docs/Web/API/Selection_API the code below works for only on change, it wraps the selected text in a span with color red window.onload = () => { p1 = document.querySelector("#p1"); changeBtn = document.querySelector("#change"); changeBtn.addEventListener("click", (event) => { const anchorOffset = window.getSelection().anchorOffset; const selected = window.getSelection().toString(); const text = window.getSelection().anchorNode.textContent; const left = text.slice(0, anchorOffset); const middle = text.slice(anchorOffset, anchorOffset + selected.length); const right = text.slice(anchorOffset + selected.length); const leftTextNode = document.createTextNode(left); const rightTextNode = document.createTextNode(right); const middleElement = document.createElement('span'); const middleTextNode = document.createTextNode(middle); middleElement.appendChild(middleTextNode); middleElement.style.color = 'red'; window.getSelection().anchorNode.parentNode.replaceChildren(leftTextNode, middleElement, rightTextNode); }); }
27th Jun 2022, 8:23 AM
ŠœŠ°Ń€Ń‚ŠøŠ½ šŸ˜‘šŸŽµ
ŠœŠ°Ń€Ń‚ŠøŠ½ šŸ˜‘šŸŽµ - avatar