READ THE EDIT AT THE BOTTOM! :)
I am making a little website where the user can fill in multiple text boxes, and when they come back later, their text boxes come back. (Pretty much a terrible helpdesk system using localstorage).
I have three fields the user can fill out, then when the fields are submitted they should appear below, in a div. Currently i am only able to get the first field to be shown, as i append it to a static div, but i want to append the rest of the fields to the first one. This wouldnt be too hard, but i cant seem to append a child to a div that doesnt have a set ID (without somehow hardcoding it).
I have tried things like
divAId + i.appendChild(divB)
And
var divAIdNumber = divAId + i;
divAIdNumber.appendChild(divB);
, but nothing seems to work.
Here is the code in question:
gradStorages = JSON.parse(localStorage.getItem('gradStorages'));
var iFeil = 0;
function feilDivCreate(){
const divF = document.createElement("div");
divF.className = "feilDiv";
divF.id = "feilDivId" + iFeil;
listIdIncrement();
divF.appendChild(document.createTextNode(set1));
textContainer2.appendChild(divF);
iFeil += 1;
}
var iOffer = 0;
var feilIdNumber = "feilId";
function offerDivCreate(){
const divO = document.createElement("div");
divO.className = "offerDiv";
divO.id = "offerDivId" + iOffer;
listIdIncrement();
divO.appendChild(document.createTextNode(set1));
feilIdNumber + iOffer.appendChild(divO);
iOffer += 1;
console.log(feilIdNumber + "TATATATAT");
}
var set1 = "set1 Not Defined";
var set2 = "set2 Not Defined";
var set3 = "set3 Not Defined";
function extract(){
for(let i = 0; i < feilStorages.length; i++){
set1 = feilStorages[i];
set2 = offerStorages[i];
set3 = gradStorages[i];
feilDivCreate();
offerDivCreate();
gradDivCreate(); // same as offerDiv
}
}
(can add more, or make a jsfiddle if needed.)
I need a way to append offerDiv to feilDiv, but its not so simple because feilDiv's id is feilDivId + i where i goes up by one for each new feildiv added.
Any tips for how i can achieve this?
EDIT: Here is a simplified version, showing all the code necessary to understand what im trying to do. https://codepen.io/kossi1337/pen/xxKPRvv
Might be easier to just make a new question with all the new code, but im not too sure if that allowed.. Let me know if i have to change anything about my question :)
In this code:
var divAIdNumber = divAId + i;
divAIdNumber.appendChild(divB);
It seems like you are trying to append an element to the Integer value you just created by adding i to some number. You need to grab the parent node, either via document.querySelector or using jQuery, then append to the parent. The browser has no idea what to do when you try to append markup to a number. It expects a DOM location that it will be appended to.
It should be like this:
var divAIdNumber = divAId + i;
var html = "<div class='" + divAIdNumber + "'> Content here </div>";
var element = document.querySelector(".my-element");
element.appendChild(html);
For a project I want to create a variable that stores all the text within the html, so pretty much everything between tags, titles, paragraphs, everything visible for a user on a webpage. However I don't want my javascript code that's between the script tag to show up in this output too.
I was trying with something like this:
var content = $("html").remove("script").text()
But this is not working.
Here it is:
First use this:
var r = document.getElementsByTagName('script');
for (var i = (r.length-1); i >= 0; i--) {
if(r[i].getAttribute('id') != 'a'){
r[i].parentNode.removeChild(r[i]);
}
}
And then:
var txt = document.body.innerText;
OR
var txt = $('body').text();
var contentDiv = $('<div/>', {
html: $('body').clone()
});
contentDiv.find('script').remove()
return contentDiv.text()
I'm looking for a way to highlight and format code snippets passed as string for a live style guide. I'm playing around with highlighjs and prettify. They are really helpful and easy for highlighting, but I can't seem to figure out a way to format or whether they can actually do that or not.
By formatting, I mean tabs and newlines to make code legible. I need to pass code as a string to automate the output of dust template I'm using for the style guide.
That is, I want to pass:
"<table><tr><td class="title">Name</td><td class="title">Category</td><td class="title">Results</td></tr></table>"
And get something like:
<table>
<tr>
<td class="title">Name</td>
<td class="title">Category</td>
<td class="title">Results</td>
</tr>
</table>
Any ideas on how to accomplish this?
Thanks!
You could parse this as HTML into a DOM and than traverse every element writing it out and indenting it with every iteration.
This code will do the job. Feel free to use it and surely to improve it. It's version 0.0.0.1.
var htmlString = '<table><tr><td class="title">Name</td><td class="title">Category</td><td class="title">Results</td></tr></table>';
//create a containing element to parse the DOM.
var documentDOM = document.createElement("div");
//append the html to the DOM element.
documentDOM.insertAdjacentHTML('afterbegin', htmlString);
//create a special HTML element, this shows html as normal text.
var documentDOMConsole = document.createElement("xmp");
documentDOMConsole.style.display = "block";
//append the code display block.
document.body.appendChild(documentDOMConsole);
function indentor(multiplier)
{
//indentor handles the indenting. The multiplier adds \t (tab) to the string per multiplication.
var indentor = "";
for (var i = 0; i < multiplier; ++i)
{
indentor += "\t";
}
return indentor;
}
function recursiveWalker(element, indent)
{
//recursiveWalker walks through the called DOM recursively.
var elementLength = element.children.length; //get the length of the children in the parent element.
//iterate over all children.
for (var i = 0; i < elementLength; ++i)
{
var indenting = indentor(indent); //set indenting for this iteration. Starts with 1.
var elements = element.children[i].outerHTML.match(/<[^>]*>/g); //retrieve the various tags in the outerHTML.
var elementTag = elements[0]; //this will be opening tag of this element including all attributes.
var elementEndTag = elements[elements.length-1]; //get the last tag.
//write the opening tag with proper indenting to the console. end with new line \n
documentDOMConsole.innerHTML += indenting + elementTag + "\n";
//get the innerText of the top element, not the childs using the function getElementText
var elementText = getElementText(element.children[i]);
//if the texts length is greater than 0 put the text on the page, else skip.
if (elementText.length > 0)
{
//indent the text one more tab, end with new line.
documentDOMConsole.innerHTML += (indenting + indentor(1) ) + elementText+ "\n";
}
if (element.children[i].children.length > 0)
{
//when the element has children call function recursiveWalker.
recursiveWalker(element.children[i], (indent+1));
}
//if the start tag matches the end tag, write the end tag to the console.
if ("<"+element.children[i].nodeName.toLowerCase()+">" == elementEndTag.replace(/\//, ""))
{
documentDOMConsole.innerHTML += indenting + elementEndTag + "\n";
}
}
}
function getElementText(el)
{
child = el.firstChild,
texts = [];
while (child) {
if (child.nodeType == 3) {
texts.push(child.data);
}
child = child.nextSibling;
}
return texts.join("");
}
recursiveWalker(documentDOM, 1);
http://jsfiddle.net/f2L82m8h/
This post was the most helpfull to understand createDocumentFragment() instead of createElement()
Should I use document.createDocumentFragment or document.createElement
I've understood that for performance reason using fragment will help on big dataset so i want to conver my function.
This is what i use right now and it works as desired => Get content from a php file with ajax and then append this content at the top of existing div#wrapperinside a new div.feedBox(r being the XMLHTTP /ACTIVE OBJECT)
r.onreadystatechange=function(){
if(r.readyState==4 && r.status==200){
//Want to convert this to createDocumentFrangment --START
var n = document.createElement("div");
n.className = "feedBox";
n.innerHTML = r.responseText;
document.getElementById("wrapper").insertBefore(n, document.getElementById("wrapper").firstChild);
//Want to convert this to createDocumentFrangment --END
}
}
This is what i tried, but what happens is the content is added but without the div.feedBox
var n = document.createElement("div");
n.className = "feedBox";
n.innerHTML = r.responseText;
var f = document.createDocumentFragment();
while (n.firstChild) { f.appendChild(n.firstChild); }
document.getElementById("wrapper").insertBefore(f, document.getElementById("wrapper").firstChild);
What did i miss? can you explain why and how to make it work?
Is this really a more efficient way of doing this?
PS: NO jquery please. I know it well and i use it widely on other project but i want this to be as small / lite / efficient as possible.
Shouldn't this line
while (n.firstChild) { f.appendChild(n.firstChild);
be
f.appendChild(n);
Also I see that you are not appending the div.feedBox to your DOM anywhere..
What happens if the while condition fails.. You are not appending anything to your DOM..
I am assuming this will work .. Not tested though
f.appendChild(n)
document.getElementById("wrapper").appendChild(f,
document.getElementById("wrapper").firstChild);
ALso better to use
.appendChild(f, instead of .insertBefore(f,
Check Fiddle
This is the full working function, any1 sould feel free to use it:
function ajax_fragment(php_file){
if (window.XMLHttpRequest){
r=new XMLHttpRequest();
} else{
r=new ActiveXObject("Microsoft.XMLHTTP");
}
r.onreadystatechange=function(){
if(r.readyState==4 && r.status==200){
var n = document.createElement("div"); //Create a div to hold the content
n.className = "feedBox"; //Give a class 'feddBox' to the div
n.innerHTML = r.responseText; //Put the response in the div
var f = document.createDocumentFragment(); //Create the fragment
f.appendChild(n); //Add the div to the fragment
//Append the fragment's content to the TOP of wrapper div.
document.getElementById("wrapper").insertBefore(f, document.getElementById("wrapper").firstChild);
}
}
r.open("GET",php_file,true);
r.send();
}
I am using a 'contenteditable' <div/> and enabling PASTE.
It is amazing the amount of markup code that gets pasted in from a clipboard copy from Microsoft Word. I am battling this, and have gotten about 1/2 way there using Prototypes' stripTags() function (which unfortunately does not seem to enable me to keep some tags).
However, even after that, I wind up with a mind-blowing amount of unneeded markup code.
So my question is, is there some function (using JavaScript), or approach I can use that will clean up the majority of this unneeded markup?
Here is the function I wound up writing that does the job fairly well (as far as I can tell anyway).
I am certainly open for improvement suggestions if anyone has any. Thanks.
function cleanWordPaste( in_word_text ) {
var tmp = document.createElement("DIV");
tmp.innerHTML = in_word_text;
var newString = tmp.textContent||tmp.innerText;
// this next piece converts line breaks into break tags
// and removes the seemingly endless crap code
newString = newString.replace(/\n\n/g, "<br />").replace(/.*<!--.*-->/g,"");
// this next piece removes any break tags (up to 10) at beginning
for ( i=0; i<10; i++ ) {
if ( newString.substr(0,6)=="<br />" ) {
newString = newString.replace("<br />", "");
}
}
return newString;
}
Hope this is helpful to some of you.
You can either use the full CKEditor which cleans on paste, or look at the source.
I am using this:
$(body_doc).find('body').bind('paste',function(e){
var rte = $(this);
_activeRTEData = $(rte).html();
beginLen = $.trim($(rte).html()).length;
setTimeout(function(){
var text = $(rte).html();
var newLen = $.trim(text).length;
//identify the first char that changed to determine caret location
caret = 0;
for(i=0;i < newLen; i++){
if(_activeRTEData[i] != text[i]){
caret = i-1;
break;
}
}
var origText = text.slice(0,caret);
var newText = text.slice(caret, newLen - beginLen + caret + 4);
var tailText = text.slice(newLen - beginLen + caret + 4, newLen);
var newText = newText.replace(/(.*(?:endif-->))|([ ]?<[^>]*>[ ]?)|( )|([^}]*})/g,'');
newText = newText.replace(/[ยท]/g,'');
$(rte).html(origText + newText + tailText);
$(rte).contents().last().focus();
},100);
});
body_doc is the editable iframe, if you are using an editable div you could drop out the .find('body') part. Basically it detects a paste event, checks the location cleans the new text and then places the cleaned text back where it was pasted. (Sounds confusing... but it's not really as bad as it sounds.
The setTimeout is needed because you can't grab the text until it is actually pasted into the element, paste events fire as soon as the paste begins.
How about having a "paste as plain text" button which displays a <textarea>, allowing the user to paste the text in there? that way, all tags will be stripped for you. That's what I do with my CMS; I gave up trying to clean up Word's mess.
You can do it with regex
Remove head tag
Remove script tags
Remove styles tag
let clipboardData = event.clipboardData || window.clipboardData;
let pastedText = clipboardData.getData('text/html');
pastedText = pastedText.replace(/\<head[^>]*\>([^]*)\<\/head/g, '');
pastedText = pastedText.replace(/\<script[^>]*\>([^]*)\<\/script/g, '');
pastedText = pastedText.replace(/\<style[^>]*\>([^]*)\<\/style/g, '');
// pastedText = pastedText.replace(/<(?!(\/\s*)?(b|i|u)[>,\s])([^>])*>/g, '');
here the sample : https://stackblitz.com/edit/angular-u9vprc
I did something like that long ago, where i totally cleaned up the stuff in a rich text editor and converted font tags to styles, brs to p's, etc, to keep it consistant between browsers and prevent certain ugly things from getting in via paste. I took my recursive function and ripped out most of it except for the core logic, this might be a good starting point ("result" is an object that accumulates the result, which probably takes a second pass to convert to a string), if that is what you need:
var cleanDom = function(result, n) {
var nn = n.nodeName;
if(nn=="#text") {
var text = n.nodeValue;
}
else {
if(nn=="A" && n.href)
...;
else if(nn=="IMG" & n.src) {
....
}
else if(nn=="DIV") {
if(n.className=="indent")
...
}
else if(nn=="FONT") {
}
else if(nn=="BR") {
}
if(!UNSUPPORTED_ELEMENTS[nn]) {
if(n.childNodes.length > 0)
for(var i=0; i<n.childNodes.length; i++)
cleanDom(result, n.childNodes[i]);
}
}
}
This works great to remove any comments from HTML text, including those from Word:
function CleanWordPastedHTML(sTextHTML) {
var sStartComment = "<!--", sEndComment = "-->";
while (true) {
var iStart = sTextHTML.indexOf(sStartComment);
if (iStart == -1) break;
var iEnd = sTextHTML.indexOf(sEndComment, iStart);
if (iEnd == -1) break;
sTextHTML = sTextHTML.substring(0, iStart) + sTextHTML.substring(iEnd + sEndComment.length);
}
return sTextHTML;
}
Had a similar issue with line-breaks being counted as characters and I had to remove them.
$(document).ready(function(){
$(".section-overview textarea").bind({
paste : function(){
setTimeout(function(){
//textarea
var text = $(".section-overview textarea").val();
// look for any "\n" occurences and replace them
var newString = text.replace(/\n/g, '');
// print new string
$(".section-overview textarea").val(newString);
},100);
}
});
});
Could you paste to a hidden textarea, copy from same textarea, and paste to your target?
Hate to say it, but I eventually gave up making TinyMCE handle Word crap the way I want. Now I just have an email sent to me every time a user's input contains certain HTML (look for <span lang="en-US"> for example) and I correct it manually.