How can i add a new class when selection with Line Break <br>
situation
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 with Line Break
<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 with Line Break <br>
then i want my structure something like this type:
<div class="container">
<div class="mySlides"> Some Text </div>
<div class="mySlides">
<div class="1stline"> Line Break Selection first line in different div class </div>
<div class="2ndline"> and the second line is in different class and other all content goes here </div>
</div>
<div class="mySlides"> Some another </div>
</div>
Means simple i want only first Line Break with different class 1stline
and then other all contents with 2ndline
class.
or if i select text without Line Break then the text should add with only mySlides
that is right now.
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.
ETC.
– RR Suthar Jan 16 '21 at 10:31