
JavaScriptを使ってボタンクリックでテキストをコピーする方法
カテゴリ:WEB制作
タグ:

今回はサイト上のテキストをJavaScriptを使ってボタンクリックでコピーする方法を紹介します。
URLやテキストなどをユーザーにコピーして使ってもらう場合などに活用できます。
コードを紹介
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>テキストコピー機能</title> <style> .text_box { margin-bottom: 20px; } </style> </head> <body> <div class="text_box"> <div> <p>テキストエリアAをコピーする</p> </div> <button>コピーする</button> </div> <div class="text_box"> <div> <p>テキストエリアBをコピーする</p> </div> <button>コピーする</button> </div> <div class="text_box"> <div> <p>テキストエリアCをコピーする</p> </div> <button>コピーする</button> </div> <script> document.addEventListener("DOMContentLoaded", function () { const buttons = document.querySelectorAll(".text_box > button"); buttons.forEach(function (button) { button.addEventListener("click", function () { const textToCopy = this.previousElementSibling.querySelector("p").textContent; navigator.clipboard.writeText(textToCopy).then(function () { alert("テキストをコピーしました!"); }).catch(function (error) { alert("テキストのコピーに失敗しました"); }); }); }); }); </script> </body> </html>
コードを解説
HTMLの解説は割愛します。
JavaScript
読み込みが完了したら実行します。
document.addEventListener("DOMContentLoaded", function () { });
HTMLで対象になるテキストとボタンの親要素に『text_box』というクラス名を付与しています。
ボタン要素を全て取得します。
const buttons = document.querySelectorAll(".text_box > button");
ループで全てのボタンにクリックイベントを設定します。
buttons.forEach(function (button) { button.addEventListener("click", function () { }); });
隣接するテキストエリアを取得します。
const textToCopy = this.previousElementSibling.querySelector("p").textContent;
『.clipboard.writeText』でテキストをコピー、アラートでユーザーにコピーできたことを知らせます。失敗した場合もアラートを出します。
navigator.clipboard.writeText(textToCopy).then(function () { alert("テキストをコピーしました!"); }).catch(function (error) { alert("テキストのコピーに失敗しました"); });
まとめ
以上、『JavaScriptを使ってボタンクリックでテキストをコピーする方法』でした。