0

Using First part of following solution I am able to copy value of the input into clipboard. but can you please let me know how about copying HTML like a entire <p>? As you can see I am getting

copyHTML.select is not a function

can you please let me know if this is doable in JS and how I can fix this?

$("#copy").on("click", function(){
      var copyText = document.getElementById("myInput");
  copyText.select();
  document.execCommand("Copy");
  alert("Copied the text: " + copyText.value);
});


$("#copyHTML").on("click", function(){
      var copyHTML = document.getElementById("sample");
  copyHTML.select();
  document.execCommand("Copy");
  alert("Copied the text: " + copyHTML.HTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" value="Hello World" id="myInput">
<button id="copy">Copy text</button>


<p id="sample" class="napper">This is atest Paragraph</p>
<button id="copyHTML">Copy HTML</button>

2
  • 1
    So...you're looking for the DOM element .outerHTML property? Commented Nov 5, 2017 at 2:40
  • yes something like clone but copying to clipboard Commented Nov 5, 2017 at 2:42

2 Answers 2

1

This will get you the HTML element.

$("#copyHTML").on("click", function(){
      var copyHTML = document.getElementById("sample");
  copyHTML.select();
  document.execCommand("Copy");
  alert("Copied the HTML (notice the .outerHTML): " + copyHTML.outerHTML);
});
Sign up to request clarification or add additional context in comments.

2 Comments

But I need to copy it to clipboard
@JJBOBO just updated the answer :) let me know if it works for you!
0

My favorite approach (no jquery):

addEventListener("focus", (event) => 
  navigator.clipboard.writeText(document.body.innerHTML)
  .then(()=>console.log("string copied to clipboard")) );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.