How can i get formatted HTML of selected part instead of simple text
Here is a script that add content to <div class="container"> </div>
when we select some text and press Get Selection button, with every time class mySlides
Okay
But here is all text goes in one by one only in this structure, even though we select any HTML text like <p> <h2>
etc part.
<div class="container">
<div class="mySlides"> Some Text </div>
<div class="mySlides"> Some other </div>
<div class="mySlides"> Some another </div>
</div>
But Now i want a little change here, my requirement is When i select text then it should be get with formatted rendered HTML Just Like This.
<div class="container">
<div class="mySlides"> Some Text </div>
<div class="mySlides">
<h3>This is heading 3</h3>
<p>
Select any part of this sentence
and press the button. Select any part of this sentence
and press the button. Select any part of this sentence
and press the button
</p>
</div>
<div class="mySlides"> Some another </div>
</div>
i also checked this but i am not able to get solve my issue. means simple i want rendered HTML format of selection.
My Whole Code IS Here:
const keySelected = new Set();
document.addEventListener('keydown', (e) => {
keySelected.add(e.which);
if(keySelected.has(17) && keySelected.has(90)){
getSelectedText();
}
});
document.addEventListener('keyup', (e) => {
keySelected.delete(e.which);
});
// Function to get the Selected Text
function getSelectedText() {
var selectedText = '';
// #### create a new element with variable (nw) #### //
var nw = document.createElement("div"); // Element's tag
nw.className = "mySlides"; // Element's class name
// some applied style
// window.getSelection
if (window.getSelection) {
selectedText = window.getSelection();
}
// document.getSelection
else if (document.getSelection) {
selectedText = document.getSelection();
}
// document.selection
else if (document.selection) {
selectedText =
document.selection.createRange().text;
} else return;
// #### get the Selected text appended to body #### //
nw.innerHTML = selectedText;
document.getElementsByClassName('container')[0].prepend(nw); // Append element to body
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container"> </div>
<button id="mybtn" onclick="getSelectedText()">Get Selection</button>
<p>
Select any part of this sentence
and press the button. Select any part of this sentence
and press the button. Select any part of this sentence
and press the button
</p>
<h3>This is heading 3</h3>
<p>
Select any part of this sentence
and press the button. Select any part of this sentence
and press the button. Select any part of this sentence
and press the button
</p>
Plz Help Me How to do that.