Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

223
Views
Copying value of <p> element to clipboard using Javascript

I'm working on a password generator which generates a random passwords and displays inside a <p> element. That part works fine.

I want to copy the output value (generated password) in the <p> element to the clipboard when the user clicks on the password value in <p>

Here's my code:

function copyPassword() {

    let password = document.getElementById("pwd").innerText
    let message = document.getElementById("msg")

    //This doesn't seem to work
    navigator.clipboard.writeText(password) 

    //This works
    message.innerText = "Copied to clipboard"
}
<p id="pwd" onclick="copyPassword()">click me</p>
<p id="msg"></p>

UPDATE: I just checked in Firefox; this code seems to work perfectly. But it doesn't on Chrome, Edge and Safari. 🤪

UPDATE 2: I uploaded the files to a GitHub repo and published. Works just fine. So no issues with the code.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

writeText es una función asíncrona, debe usar then para obtener el resultado.

And Chrome has some limitations, you may see an error message if it crashes.

 function copyPassword() { let password = document.getElementById("pwd").innerText( let message = document.getElementById("msg")); //This doesn't seem to work navigator.clipboard.writeText(password) .then(() => { //This works; message.innerText = "Copied to clipboard" }) .catch((err) => { message.innerText = err.message }) }
 <span id="pwd" onclick="copyPassword()">click me</span> <span id="msg">Respuesta</span>

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!