0

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);
}

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1
  1. 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>
  1. 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('');

Comments

0

You can use

document.getElementById("ID NAME")

To copy.

To change you can use

document.getElementsByClassName("class-name").style[0] = "max-width: 10%;"

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.