Home > Back-end >  Event reverses tag
Event reverses tag

Time:08-05

A dizzying question for experts. When I click on my <span> in the my ul it's font-style becomes unset, i.e. reset. How do I save my charming font-styles against evil 'events'?

let ul = document.querySelector('ul')

ul.addEventListener('click', function (evn) {
  let li = evn.target.closest('li');
  if (evn.target !== this) li.textContent  = '!'
})
.i {
    font-style: italic;
 }
<ul>
    <li>hello text bye</li>
    <li>hello text bye</li>
    <li>hello <span >text</span> bye</li>
</ul>

Thanks in advance

CodePudding user response:

Doing

li.textContent  = '!'

is like doing

const origText = li.textContent;
li.textContent = origText   '!'

And assigning to the .textContent of an element always inserts text only, in the form of a text node - no elements will ever be produced. If the parent originally had an element child, the element will be replaced with only its text.

For the same reason, the button disappears below:

document.querySelector('button').addEventListener('click', (e) => {
  e.target.parentElement.textContent  = '';
});
<div>
  <button>click</button>
</div>

Use .insertAdjacentText instead of .textContent =.

let ul = document.querySelector('ul')

ul.addEventListener('click', function (evn) {
  let li = evn.target.closest('li');
  if (evn.target !== this) li.insertAdjacentText('beforeend', '!');
})
.i {
    font-style: italic;
 }
<ul>
    <li>hello text bye</li>
    <li>hello text bye</li>
    <li>hello <span >text</span> bye</li>
</ul>

CodePudding user response:

Since you're modifying the .textContent itself, all inner html that's not text is stripped away. You can add a new text node to make this work. Note that this can clog up html, so if the last node is already a text node, just add to it.

let ul = document.querySelector('ul')

ul.addEventListener('click', function (evn) {
  let li = evn.target.closest('li');
  if (evn.target !== this) {
    const lastNode = [...li.childNodes].at(-1);
    if (lastNode.nodeType === 3) lastNode.textContent  = "!";
    else li.append("!");
  }
})
.i {
    font-style: italic;
 }
<ul>
    <li>hello text bye</li>
    <li>hello text bye</li>
    <li>hello <span >text</span> bye</li>
</ul>

  • Related