Hi so I created this code that works great.
document.getElementById("file").addEventListener('click',
function () {
var textArea = document.getElementById("newTextArea");
//Retrieve the selected text :
var selText = window.getSelection();
var text = textArea.innerHTML;
// I need to make a condition here. If the text doesn't have a span tag then do this:
if (document.querySelector('.test') === null) {
textArea.innerHTML = text.replace(selText, '<span class="test">'+selText+'</span>');
// if the text does have a span tag then remove the span tag
} else if (document.querySelector('.test') !== null) {
var deSelText = document.querySelector('.test');
var highlightedText = deSelText.innerHTML;
var parent = deSelText.parentNode;
var newNode = document.createTextNode(highlightedText);
parent.insertBefore(newNode, deSelText);
parent.removeChild(deSelText);
}
}, false);
But I would like to make the anonymous function into a named function so it looks like this:
document.getElementById("file").addEventListener('click', classAndSpan(test), false);
here is the named function:
function classAndSpan(addClass) {
var textArea = document.getElementById("newTextArea");
//Retrieve the selected text :
var selText = window.getSelection();
var text = textArea.innerHTML;
// I need to make a condition here. If the text doesn't have a span tag then do this:
if (document.querySelector('.' + addClass) === null) {
textArea.innerHTML = text.replace(selText, '<span class="' + addClass + '">'+selText+'</span>');
// if the text does have a span tag then remove the span tag
} else if (document.querySelector('.' + addClass) !== null) {
var deSelText = document.querySelector('.' + addClass);
var highlightedText = deSelText.innerHTML;
var parent = deSelText.parentNode;
var newNode = document.createTextNode(highlightedText);
parent.insertBefore(newNode, deSelText);
parent.removeChild(deSelText);
}
}
I'm missing something because this named function is not working. Do I return something in the function and if so what do I return?
Thanks for the help, very much appreciated.