5

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?

Community
  • 1
  • 1
ST80
  • 2,679
  • 9
  • 34
  • 75

3 Answers3

4

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

David Hedlund
  • 121,697
  • 28
  • 196
  • 213
1

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 , 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.

Ja͢ck
  • 161,074
  • 33
  • 239
  • 294
1

It is beacause the document.querySelector only return the first matched element. You can use document.querySelectorAll instated.

Wish it can help you.

Tracholar Zuo
  • 452
  • 2
  • 8
  • 1
    Welcome to stackoverflow.This post might answer the question.But a little more explanation might help out the fellow programmers to understand how it works. – Nagama Inamdar Dec 11 '14 at 12:51