jquery 如何< dds>< /dds>通过单击document.querySelector('dds')段落中特殊单词来附加标签;

w6lpcovy  于 2023-06-29  发布在  jQuery
关注(0)|答案(1)|浏览(178)
Again when the second word is clicked
  Delete the first word tag and create the second word tag

var card = document.querySelector('dds');

z18hc3ub

z18hc3ub1#

最简单的方法是为每个单词使用span,并通过将其 Package 在所需的标记中来为其给予一个click事件

const test = document.querySelector('#test');
const html = test.innerHTML;
const words = html.split(/ /);
let newHtml = '';

for (var i = 0; i < words.length; i++) {
  newHtml += '<span>' + words[i] + '</span> ';
}
test.innerHTML = newHtml;

test.querySelectorAll('span').forEach(el => {
  el.addEventListener('click', (e) => {
    if (e.target.parentElement.nodeName !== 'DDS') {
      const wrapper = document.createElement('dds');
      // insert wrapper before el in the DOM tree
      e.target.parentNode.insertBefore(wrapper, e.target);
      // move el into wrapper
      wrapper.appendChild(e.target);
    }
  });
});
dds{
  color:red;
}
<p id="test">This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission.
</p>

相关问题