How to copy and paste HTML/text by JavaScript - javascript

I want to copy a text that has the CSS class copytext
and want to paste on the same page that's has CSS class pastehere.
I am using the following code, but with no result.
function copyToClipboard(text) {
const elem = document.createElement('.copytext');
elem.value = text;
document.body.appendChild(elem);
elem.select();
document.execCommand('.pastehere');
document.body.removeChild(elem);
}

I think you want to get the value of an HTML tag or something? with DOM Element innerHTML you can get the value of the Tag. eg:
html:
`<p id="myTag">hello world</p>`
javascript:
`let var1 = document.getElementById("myTag").innerHTML;`
the 'hello world' is now stored in the variable 'var1' and you can continue to work with it normally

If you want to copy text from all elements .copytext to the element .pastehere:
HTML:
<div class="copytext">Line 1</div>
<div class="copytext">Line 2</div>
<div class="copytext">Line 3</div>
JS:
function fun(text){
let copiedText = "";
text.forEach(element => {
copiedText += element.textContent + "\n";
});
const resault = document.createElement('div');
resault.classList.add('pastehere');
resault.innerText = copiedText;
document.body.appendChild(resault);
}
let copyFrom = document.querySelectorAll('.copytext');
fun(copyFrom);
You'll get:
<div class="pastehere">
Line 1 <br>
Line 2 <br>
Line 3 <br>
</div>
If you want to create element with the text you pass to the function as an argument:
JS:
function fun(text){
let resault = document.createElement('div');
resault.classList.add('pastehere');
resault.innerText = text;
document.body.appendChild(resault);
}
let text = "My text";
fun(text);
You'll get:
<div class="pastehere">
My text
</div>
!! Note that you can only type a tag name in document.createElement('');

You can use
document.getElementById("ID NAME")
To copy.
To change you can use
document.getElementsByClassName("class-name").style[0] = "max-width: 10%;"

Related

Why the error alert still displayed event the HTML elements are sanitized?

The below are my use case scenario.
Collect the user input.(the input must be HTML sting element)
Form the HTML element with some style.
After creating the HTML element, need to sanitize it and append it into the target DOM element.
The DOM element rendered the sanitized element. but the error alert stil displayed.
The user input is
<img src="http://url.to.file.which/not.exist" onerror="alert(document.cookie);">
This always shows the alert.
Can someone help me to resolve this?
function createEle() {
const wrapElement = document.createElement('div');
wrapElement.innerHTML = document.getElementById("html-input").value;
const html = showSanitizedHTML(wrapElement);
console.log(html.outerHTML)
document.getElementById("sanitized-html").innerHTML = html.innerHTML;
}
function showSanitizedHTML(value) {
const sanitizedHTML = DOMPurify.sanitize(value.outerHTML);
const tempWrapElement = document.createElement('div');
tempWrapElement.innerHTML = sanitizedHTML;
return tempWrapElement.firstElementChild;
}
<script src="https://cdn.jsdelivr.net/npm/dompurify#2.0.16/dist/purify.min.js"></script>
<textarea id="html-input"></textarea>
<button onclick="createEle()">Show Sanitized HTML</button>
<div id="sanitized-html"></div>
The script content executes on this statement
wrapElement.innerHTML = document.getElementById("html-input").value;
So here is how to fix it
function createEle() {
const wrapElement = document.createElement('div');
wrapElement.innerHTML = DOMPurify.sanitize(document.getElementById("html-input").value);
console.log(wrapElement.outerHTML)
document.getElementById("sanitized-html").innerHTML = wrapElement.innerHTML;
}
<script src="https://cdn.jsdelivr.net/npm/dompurify#2.0.16/dist/purify.min.js"></script>
<textarea id="html-input"></textarea>
<button onclick="createEle()">Show Sanitized HTML</button>
<div id="sanitized-html"></div>
or shorter, assuming you want to keep using the wrapper:
document.getElementById("sanitized-html").innerHTML = wrapElement.innerHTML;
This is the sequence of events:
You read the raw user input
You inject the raw user input into the DOM (wrapElement.innerHTML =)
You read the normalised user input back from the DOM
You pass the normalised user input though DOMPurify.sanitize
You inject the sanitized user input into the DOM
The alert fires due to step 2.
Because you're using unsanitized HTML here:
const wrapElement = document.createElement('div');
wrapElement.innerHTML = document.getElementById("html-input").value;
Don't jump through those hoops, just pass the text directly to DOMPurify:
function createEle() {
const element = showSanitizedHTML(document.getElementById("html-input").value);
// Your `showSanitizedHTML` is returning an **element**, not HTML,
// so you wouldn't use `innerHTML` to put it in the DOM.
const output = document.getElementById("sanitized-html");
output.innerHTML = "";
output.appendChild(element);
}
function showSanitizedHTML(html) {
const sanitizedHTML = DOMPurify.sanitize(html);
// Not sure what the purpose of this wrapper element is, but since
// it only uses sanitized HTML, I left it in place.
const tempWrapElement = document.createElement("div");
tempWrapElement.innerHTML = sanitizedHTML;
return tempWrapElement.firstElementChild;
}
<script src="https://cdn.jsdelivr.net/npm/dompurify#2.0.16/dist/purify.min.js"></script>
<textarea id="html-input"></textarea>
<button onclick="createEle()">Show Sanitized HTML</button>
<div id="sanitized-html"></div>
Or more simply:
function createEle() {
const html = showSanitizedHTML(document.getElementById("html-input").value);
document.getElementById("sanitized-html").innerHTML = html;
}
function showSanitizedHTML(html) {
const sanitizedHTML = DOMPurify.sanitize(html);
return sanitizedHTML;
}
<script src="https://cdn.jsdelivr.net/npm/dompurify#2.0.16/dist/purify.min.js"></script>
<textarea id="html-input"></textarea>
<button onclick="createEle()">Show Sanitized HTML</button>
<div id="sanitized-html"></div>
Or even more simply:
function createEle() {
document.getElementById("sanitized-html").innerHTML = DOMPurify.sanitize(
document.getElementById("html-input").value
);
}
<script src="https://cdn.jsdelivr.net/npm/dompurify#2.0.16/dist/purify.min.js"></script>
<textarea id="html-input"></textarea>
<button onclick="createEle()">Show Sanitized HTML</button>
<div id="sanitized-html"></div>

How can i add multi lines together into different different div / span tag through this text box?

How can i add multi lines together into different different span tag through this text box ?
There is an text box, by using this box i can insert a new div / span class content Right ?
But every time when i need to add new class i need to write a new line in this text box and need to press send button, Now i want that if i have 10 lines content together with "Enter" button line break
Like
My Line 1 is here
My Line 2 is here
My Line 3 is here
My Line 4 is here
My Line 5 is here
My Line 6 is here
My Line 7 is here
My Line 8 is here
... and so on
then i want to paste all 10 lines in this text box together and by pressing send button i want that all lines must be add in different different div / span class not all in one class with < br > tag that is working now.
so plz help me to improve my code
Love you Helper and Thanks in Advance
const sendButton = document.getElementById('send-btn');
const textArea = document.getElementById('input');
const innerDiv = document.getElementById('inner');
var message = textArea.value;
sendButton.addEventListener('click', function () {
const message = new MessageContainerBuilder().BuildMessage(textArea.value);
innerDiv.appendChild(message);
textArea.value = '';
});
function encodeHtmlEntity(input) {
var output = input.replace(/[\u00A0-\u9999<>\&]/gim, function (i) {
return '&#' + i.charCodeAt(0) + ';';
});
return output;
}
function MessageContainerBuilder() {
var createDivElement = function (classTest) {
var div = document.createElement('div');
var classAttr = document.createAttribute('class');
classAttr.value = classTest;
div.setAttributeNode(classAttr);
return div;
};
var createSpanElement = function (value, classTest) {
var span = document.createElement('span');
if (classTest) {
var classAttr = document.createAttribute('class');
classAttr.value = classTest;
span.setAttributeNode(classAttr);
}
span.innerText = encodeHtmlEntity(value);
return span;
};
this.BuildMessage = function (text) {
var divContainer = createDivElement('outgoing');
var messageSpan = createSpanElement(text, 'me');
divContainer.appendChild(messageSpan);
return divContainer;
};
}
<div id="inner">
<div class="incoming">
<div class="them">Lorem
</div>
</div>
<div class="outgoing">
<div class="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">Send</button>
so plz help me to improve my code
Love you Helper and Thanks in Advance
I took some liberties and simplified your code as you can see below. It does everything I believe your code was attempting.
Note that I'm using .split("\n") to break your input based on each newline character and then iterate over that as necessary.
Also, you said you were inserting a div/span, but I don't see your code actually creating a span tag. I wrote my code to do that for you though.
const sendButton = document.getElementById('send-btn');
const textArea = document.getElementById('input');
const innerDiv = document.getElementById('inner');
var message = textArea.value;
sendButton.addEventListener('click', function() {
// split the textarea entries into an array
let lines = (textArea.value).split("\n");
// iterate over each line, creating a div/span and inserting into the DOM
lines.forEach( (line) => {
let encodedLine = encodeHtmlEntity(line);
let newElement = `<div class="me"><span>${encodedLine}</span></div>`;
innerDiv.innerHTML += newElement;
});
// reset the textarea
textArea.value = '';
});
function encodeHtmlEntity(input) {
var output = input.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#' + i.charCodeAt(0) + ';';
});
return output;
}
<div id="inner">
<div class="incoming">
<div class="them">Lorem
</div>
</div>
<div class="outgoing">
<div class="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">Send</button>
You can try using String.prototype.split() so that each text is separated by \n (new line) into an array, then you can iterate over each element like using Array.prototype.forEach(). Here's the code you can use:
sendButton.addEventListener('click', function () {
textArea.value.split('\n').forEach((text) => {
const message = new MessageContainerBuilder().BuildMessage(text);
innerDiv.appendChild(message);
});
textArea.value = '';
});

Is it possible to put another div or HTML element replacing "Hello World" text?

<body onload="myfunction('target')"><div id="target"> "Hello World" </div></body>
Is It Possible To Put Another Div Or HTML Element Replacing "Hello World" Text?
Hello World is a Left To Right Marquee Text
<script language="javascript">
function myfunction(id) {
var element = document.getElementById(id);
var textnode = element.childNodes[0];
var text = textnode.data;
setInterval(function() {
text = text[text.length - 1] + text.substring(0, text.length - 1);
textnode.data = text;
}, 400)
}
</script>
If you're just trying to replace the text that is in the innerHTML/innerText querying the HTML element and simply setting it's innerHTML/innerText to the new value will suffice.
Example:
const myElement = document.getElementByTagName('h1')
myElement[0].innerHTML = 'new value'
if you want to change html inside div and change to another div or text or any html
you can do like this you don't need to replace
$('#target').html('<div class="col-md-2"></div>');
and if you want to replace then you can do like this
$('#target').html().replace("hello",'<div class="col-md-2"></div>');
innerHTML should do the trick, if you are trying to add html elements:
Here is the working example of your code snippet:
https://codebrace.com/editor/b15cd15b3
Example:
...
element.innerHTML = "<span style='color: red; background-color:yellow;'>" + text + "</span>";
...
html code
<body onload="myfunction()">
<div id="target"> Hello World </div>
</body>
javascript code
function myFunction() {
var str = document.getElementById("target").innerHTML;
var res = str.replace("Hello World", "testing");
document.getElementById("target").innerHTML = res;
}
myFunction();
Replacing the helloworld html to testing html using onload function.

Deleting the last Element in a Div [JavaScript]

I'm having a strange problem. I'm trying to make a program that will add and delete div's inside another div called "body". To add divs, I use document.getElementById("body").innerHTML. Adding works fine. However, in the deleting function, I replace the "body" id with a variable with the id of the div that will be deleted. But when I run the code, I get the error "cannot set innerHTML of null". I tried to replace the id variable with a fixed local variable, and it worked fine. I also tried to add quotes to the variable but that didn't work either. Is there any reason why I can't set the id to a changing variable? Thanks.
Here is my code:
var i = 1;
function myFunction() {
var addDiv = document.getElementById("body2");
addDiv.innerHTML += "<div id = '" + i + "'><br><textarea id = '1' > foo < /textarea></div > ";
i++;
}
function myFunction2() {
var deleteDiv = document.getElementById(i);
deleteDiv.innerHTML = "";
i--;
}
<div id="body2">
<div id="0">
<textarea id="text">lol</textarea><button onclick="myFunction()">Add</button>
<button onclick="myFunction2()">Delete</button>
</div>
</div>
you are incrementing i after adding a div so you must use i-1 while deleting to get correct id.
var i = 1;
function myFunction() {
var addDiv = document.getElementById("body2");
addDiv.innerHTML += "<div id = '"+i+"'><br><textarea id = '1'>foo</textarea></div>";
i++;
}
function myFunction2() {
var deleteDiv = document.getElementById(i-1);
deleteDiv.remove();
i--;
}
<div id = "body2">
<div id = "0">
<textarea id = "text">lol</textarea><button onclick =
"myFunction()">Add</button>
<button onclick = "myFunction2()">Delete</button>
</div>
</div>
To remove last child, you can even use CSS selector last-child. You should also add specific class to newly added divs as you would want to remove only newly added divs.
This will also remove dependency of i.
As an addon, you can also use document.createElement + Node.appendChild instead of setting innerHTML. .innerHTMl will be expensive for highly nested structure.
function myFunction() {
document.getElementById("body2").appendChild(getDiv());
}
function getDiv(i){
var div = document.createElement('div');
div.classList.add('inner')
var ta = document.createElement('textarea');
ta.textContent = 'foo';
div.appendChild(ta);
return div;
}
function myFunction2() {
var div = document.querySelector('#body2 div.inner:last-child')
div && div.remove()
}
<div id="body2">
<div id="0">
<textarea id="text">lol</textarea><button onclick="myFunction()">Add</button>
<button onclick="myFunction2()">Delete</button>
</div>
</div>
You can refer "innerHTML += ..." vs "appendChild(txtNode)" for more information.

Adding elements using browser console

I'm trying to add an element in a webpage using the browser console.
My element is something like:
<a class="myclass" role="myrole" href="/url.com">
<span class="Label">Hello World</span>
</a>
How can I do this ?
document.getElementById('myid').innerHTML = "<a class='myclass' role='myrole' href='/url.com'><span class='Label'>Hello World</span></a>";
You can add a dummy div or tag with some ID and use this code
HTML:
<div id="myid">
</div>
function addElem(elem, text)
{
var elem = document.createElement(elem), // element to be created
text = document.createTextNode(text); // text node
bd = document.body; // get body
elem.appendChild(text); // elem appended with text
bd.appendChild(elem); // body appended with elem
return elem;
}
call it as so: addElem('p', 'text here');
call from console and see :)
try here itself
open your console,
var _el = '<a class="myclass" role="myrole" href="/url.com"><span class="Label">Hello World</span></a>';
$('.post-text').append(_el);

Categories