Q202819
by jun68ykt
HTML
<table id="preview">
<tr>
<td style="text-align: left" class="_con">
<div class="nested">
<span>インダス文明誕生インダス文明誕生インダス文明誕生</span>
<a href="https://ja.wikipedia.org/wiki/"><span>インダス文明誕生インダス文明誕生</span></a>
<span>インダス文明誕生</span>
</div>
</td>
</tr>
</table>
<button id="unwrap_btn"><a>を除去</button>
<button id="wrap_btn"><a>で囲む</button>
CSS
table { border: solid 1px #000; margin-bottom: 30px; }
button { font-size: 16pt; }
JavaScript
$(function() {
// span が a で囲まれていれば、その a を除去する。
$('#unwrap_btn').click(function() {
const htmlAfter =
$('div.nested')
.html()
.split('\n')
.map(line => /<a\s+[^>]+>(.+)<\/a>/.exec(line) ? RegExp.$1 : line)
.join('\n');
$('div.nested').html(htmlAfter);
});
// span が a で囲まれていなければ、それを a で囲む。
$('#wrap_btn').click(function() {
const htmlAfter =
$('div.nested')
.html()
.split('\n')
.map(line =>
/^\s*(<span>[^<]+<\/span>)/.exec(line) ?
`<a href="https://ja.wikipedia.org/wiki/">${RegExp.$1}</a>` : line)
.join('\n');
$('div.nested').html(htmlAfter);
});
});