How to remove span onclick or on modify? - javascript

How do I write a JS function to remove the span on click and just retain the inner text ?
​<span class="test" onclick="removespan(this);">Data in red</span>
​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
​removespan = function(e)​{
alert(e.innerText);
}​
CSS : ​span.test{color:red;}
onclick I would like to remove the span and just retain the inner text .
Infact I would like to have a onmodify event ...that removes the span .
The purpose is to remove a spellchecker span class in WYSIWYG editor .

If the span is the only child element inside its parent node
<div>
<span class="test" onclick="removespan(this);">Data in red</span>
</div>
removespan = function(span) {
span.parentNode.innerHTML = span.innerHTML;
}
Otherwise use this function
removespan = function(span) {
span.parentNode.replaceChild(document.createTextNode(span.innerHTML), span);
}

In case anyone is interested in an "expanded" version of Diode's second option:
function removespan(span) {
// Get the text contents of the clicked span
var span_contents = span.innerHTML;
// Get the parent node of the clicked span
var span_parent = span.parentNode;
// Create a new text node in the DOM to hold the text contents
var text_node = document.createTextNode(span.innerHTML);
// Replace the clicked span node with your newly created text node
span_parent.replaceChild(text_node, span);
// Alternatively, do the above in one line...
// span.parentNode.replaceChild(document.createTextNode(span.innerHTML), span);
}

<span id="test"></span>
y=doc.getElementsById("test");
y.getParent().removeChild(y);

Related

Selected text remove element already wrapped in a span

I have a scenario/dilemma, I am a little stuck trying to figure out. Below will be my best of a visual representation.
1. I select
This is dummy text to select
2. I bold and it gets wrapped with a span
This is dummy text to select
<h2 This is dummy <span style="font-weight: 700;">text to select</span></h2>
3. Now lets say I want to select some text but we know it's already wrapped in a span
This is dummy [BOLD]text[BOLD] to select
4. Its a crossover with selected text, so now my code. In my important comment, I can identify that the element is found in the selection. But how can I find it and then remove the span.
const el = document.createElement('span');
function handleNodeWrap(){
if(selection?.containsNode(el,true)){
//! IMPORTANT find and remove element of selected text
}
surroundSelection(el);
}
Here's one approach to remove the span from the selected text:
const el = document.createElement('span');
function handleNodeWrap() {
if (selection?.containsNode(el, true)) {
// find parent node of the selected text
let parentNode = selection.anchorNode.parentNode;
// create a new range that selects the entire content of the parent node
let range = document.createRange();
range.selectNodeContents(parentNode);
// replace the content of the parent node with the plain text version
let text = range.extractContents().textContent;
parentNode.textContent = text;
} else {
surroundSelection(el);
}
}

how to find the child node element of a div "contenteditable" where the cursor is writing on input event handler

I am trying to create a custom textarea editor by adding contenteditable as attribute on a div element that the text will be as text element and hashtag will be as span element, but the problem is when i want to add a hashtag between text and hashtag, to do that must to find the current index of child element that the cursor is writing, and then i can use inderBefore method to add this element after this index thanks
my html code:
<div class="text">
<div #textarea class="textarea" contenteditable="true"
(input)="onchangeText($event)" (focusin)="toggleFocus()" (focusout)="toggleFocus()" >
that is a post <span class="hashtag">#hashtag</span> try to add hashtag at the
<span class="hashtag">#beginig</span> will be add as last child to the and
</div>
<div class="placeholder" *ngIf="checkPlaceHolder()" (click)="onclickPlaceHolder($event)"
[ngStyle]="{opacity:focus? 0.5 : 1}">
What do you want to share?
</div>
</div>
here is my input event handler:
onchangeText(event) {
// on input event handler
if (this.isAfterHashtag()) {
this.onAddElement(event.data, "text"); //add new element
}
if (this.isHashtag(event.data)) {
// if character is # hashtag
this.onAddElement(event.data, "hash");
}
this.setText();
if (this.checkPlaceHolder()) {// if the length of textare is 0
this.textarea.nativeElement.innerHTML = "";
}
}
here is my addElementMethod:
onAddElement(text, type) {
this.removeLastCharacter();
if (type === "hash") {
// add element for hash tag
const span: HTMLParagraphElement = this.renderer.createElement("span");
span.innerHTML = text;
this.renderer.addClass(span, "hashtag");
this.renderer.appendChild(this.textarea.nativeElement, span);
//must use insertBefore method, but before it must find index of child elemenet where to add it
// this.renderer.insertBefore( this.textarea.nativeElement , p , this.textarea.nativeElement.children[1] );
} else if (type === "text") {
// add element for text
const textNode = this.renderer.createText("");
textNode.textContent = text;
this.renderer.appendChild(this.textarea.nativeElement, textNode);
}
this.setText();
this.setCursorToEnd();
}
here is an example:
custom textarea editor

jQuery: How to select text between two closed html tags

I am trying to wrap the intro/help text in html document using jQuery.It is not inside any tag but between two closed html tags.
Please see attached code snippet for example. the 2nd end tag can also be other than <p>.
var txtHelp = jQuery('b.page-title').nextUntil('p').text();
console.log(txtHelp);
//jQuery('b.page-title').nextUntil('p').text().wrap("<p />");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b class="page-title"><h4>System Log</h4><hr class="text-primary"></b>
How to select this text and wrap it in new P-Tag
<p align="center">This can by any html tag</p>
The nextUntil() method not selects textnodes.
You can get the text node by nextSibling property of node and get text content by textContent property of text node.
var txtHelp = jQuery('b.page-title')[0] // get the dom object
.nextSibling // get the text node next to it
.textContent; // get text content
console.log(txtHelp);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b class="page-title"><h4>System Log</h4><hr class="text-primary"></b>
How to select this text and wrap it in new P-Tag
<p align="center">This can by any html tag</p>
UPDATE 1 : If you want to wrap the element by a p tag then do it like.
$( // wrap by jquery to convert to jQuery object
$('b.page-title')[0] // get the dom element also you can use `get(0)`
.nextSibling // get the textnode which is next to it
).wrap('<p/>'); // wrap the element by p tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b class="page-title"><h4>System Log</h4><hr class="text-primary"></b>
How to select this text and wrap it in new P-Tag
<p align="center">This can by any html tag</p>
UPDATE 2 : If it contains br tag and you want to include it as a text then do something tricky using contents() method.
var get = false;
$($('b.page-title')
.parent() // get it's parent
.contents() // get all children node including text node
.filter(function() {
if ($(this).is('b.page-title')) {
get = true; // if element is 'b.page-title' then set flag true , we need to get element from here
return false // return false that we don't need the 'b.page-title'
}
if ($(this).is('p')) // check element is `p`, that we need to get element uptop tag
get = false; // update flag
return get; // return the flag for filtering
})).wrapAll('<p/>'); // use wrapAll to wrap all elements withing single tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b class="page-title"><h4>System Log</h4><hr class="text-primary"></b>
How to select this text
<br/>and wrap it in new P-Tag
<p align="center">This can by any html tag</p>
For a pure jQuery approach, you can try this:
var contents = $('b.page-title').contents(),
textNodes = contents.filter(function() { return this.nodeType === 3; });
console.log(textNodes[0].textContent);
See contents()

Adding html code instead of plain text to ul with appendchild or other method?

document.getElementById('addplace').addEventListener('click', function() {
addplace();
});
function addplace () {
var node = document.createElement("li"); // Create a <li> node
var textnode = document.createTextNode("<b>Waypoint</b>"); // Create a text node
node.appendChild(textnode); // Append the text to <li>
document.getElementById("waypoints").appendChild(node);
}
<input type="submit" id="addplace" value="Add One!">
<ul id="waypoints">
</ul>
I need this to make the html code work in each new li. I tried innerHTML as well and was only able to add plain text. How to make "Waypoint" bold instead of it showing the text "Waypoint" enclosed by b tags?
It's specifically for adding a new Google Places autocomplete field and an image of an "x" to delete the li so i'm looking for a solution that can pass values / be JavaScript friendly for the rest of my application mentioned in this question.
Thanks
Instead of creating a text node, create a node for <b> tag and set its text content.
function addplace () {
var node = document.createElement("li"); // Create a <li> node
var textNode = document.createElement("b"); //create a <b> tag
textNode.textContent = "Waypoint"; //set <b> tag's text
node.appendChild(textnode); //Append the <b> tag
document.getElementById("waypoints").appendChild(node);
}
DEMO
If you want to set different html elmenets inside of li more than a <b> element, then you could use the below,
function addplace() {
var node = document.createElement("li"); // Create a <li> node
node.innerHTML = "<b>waypoints</b>"
document.getElementById("waypoints").appendChild(node);
}
DEMO

Why won't this script append a child div element?

When I click on the p element with an onclick attribute calling the make_child function I would expect it to append a div element when ever it is clicked but it seams to be only appending a text node to the paragraph element what is the cause of this?
<script type="text/javascript">
function make_child(text, id, type) {
var text = document.createTextNode(text);
var target = document.getElementById(id);
var add = document.createElement(type);
var addtext = add.appendChild(text);
target.appendChild(addtext);
}
</script>
<p id="changeme" onclick="make_child('I have changed', 'changeme', 'div')">Click me to change</p>
change the last line to this
target.appendChild(add);
now you are appending to the correct element
Try doing target.appendChild(add) instead of target.appendChild(addtext)
Edit (more detail):
The syntax for appendChild (from MDN) is:
var child = element.appendChild(child);
Where child is the element being appended. In this case, addtext = add.appendChild(text) is set to text rather than add. Just doing target.appendChild(add) should solve this problem.
This also means the variable addtext is useless; you can remove it leaving only
add.appendChild(text)
for that line.

Categories