I try to paste text into multiple fields, but the formatting is only cleared on the first element, not the second etc.
I found this question https://stackoverflow.com/a/12028136/3955607 which works fine, but again, on multiple elements it doesnt work.
So I got this HTML
<div style="color:red">Some <em>rich</em> <span style="font-size:2em">HTML</span></div>
<br />
<div style="border:1px solid red" contenteditable></div>
<br />
<div style="border:1px solid red" contenteditable></div>
and this javascript:
document.querySelector("div[contenteditable]").addEventListener("paste", function(e) {
e.preventDefault();
var text = e.clipboardData.getData("text/plain");
document.execCommand("insertHTML", false, text);
});
I have this fiddle http://jsfiddle.net/tdjuc8es/
just copy and paste the Some rich HTML
- text and see what happens
Someone who can help me out?
document.querySelector
yields one element. You want to use document.querySelectorAll
to get all matching elements, and then iterate over that collection.
var editors = document.querySelectorAll('div[contenteditable]');
for(var i = 0, l = editors.length; i < l; i++) {
editors[i].addEventListener('paste', myCustomPasteFunction);
}
Fiddle
If you're used to jQuery, you might think that document.querySelector()
fulfils the same kind of function; however, it only returns the first element that matches the selector; instead you should have used document.querySelectorAll()
and then used iteration to add your event handlers.
Since you've tagged it as jquery, you could also consider this:
$("div[contenteditable]").on("paste", function(e) {
e.preventDefault();
var text = e.originalEvent.clipboardData.getData("text/plain");
document.execCommand("insertHTML", false, text);
});
div[contenteditable] {
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="color:blue">Some <em>rich</em> <span style="font-size:2em">HTML</span></div>
<br />
<div style="border:1px solid red" contenteditable></div>
<br />
<div style="border:1px solid red" contenteditable></div>
I'm using e.originalEvent
here because the one that jQuery passes you in the event handler is a wrapper object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With