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);
}
CodePudding user response:
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
CodePudding user response:
You can use
document.getElementById("ID NAME")
To copy.
To change you can use
document.getElementsByClassName("class-name").style[0] = "max-width: 10%;"
CodePudding user response:
- If you want to copy text from all elements
.copytext
to the element.pastehere
:
HTML:
<div >Line 1</div>
<div >Line 2</div>
<div >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 >
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 >
My text
</div>
!! Note that you can only type a tag name in document.createElement('');