リンクを作成しテキストで出力
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./script.js" defer></script>
<link rel="stylesheet" href="./style.css">
<title>Document</title>
</head>
<body>
<div id="target"></div>
<div>
<button id="copy">Copy</button>
<p id="message_box"></p>
<pre><code id="textarea"></code></pre>
</div>
</body>
</html> function createLinkList(links, class_name) {
const ul = document.createElement('ul');
ul.className = class_name;
links.forEach(({ url, text, blank }) => {
const li = document.createElement('li');
const a = document.createElement('a');
a.href = url;
a.textContent = text;
if (blank) {
a.target = "_blank";
a.rel = "noopener noreferrer";
}
li.appendChild(a);
ul.appendChild(li);
});
return ul;
}
function formatUlHtml(ul) {
const className = ul.className || "";
const lines = [];
lines.push(`<ul${className ? ` class="${className}"` : ""}>`);
[...ul.children].forEach(li => {
lines.push(` ${li.outerHTML}`);
});
lines.push(`</ul>`);
return lines.join('\n');
}
async function copyText(text) {
if (!text) {
return "コピーする内容がありません。";
}
try {
await navigator.clipboard.writeText(text);
return "コピーしました。";
} catch {
return "コピーに失敗しました。";
}
}
const links = [
{ url: "https://yahoo.co.jp", text: "yahoo", blank: true },
{ url: "https://www.google.com/", text: "google" }
];
window.addEventListener('DOMContentLoaded', () => {
const target = document.getElementById('target');
const codeView = document.getElementById('textarea');
const copyBtn = document.getElementById('copy');
const messageBox = document.getElementById('message_box');
const className = "external-link";
const ul = createLinkList(links, className);
target.appendChild(ul);
const formattedHtml = formatUlHtml(ul);
codeView.textContent = formattedHtml;
copyBtn.addEventListener('click', async () => {
const message = await copyText(formattedHtml);
messageBox.textContent = message;
});
}); 作成されるHTMLのテキストデータは以下のようになります。
<ul class="external-link">
<li><a href="https://yahoo.co.jp" target="_blank" rel="noopener noreferrer">yahoo</a></li>
<li><a href="https://www.google.com/">google</a></li>
</ul>