Home > OS >  How to make a span, which will be overlined by clicking the link, so that the link will be to the ri
How to make a span, which will be overlined by clicking the link, so that the link will be to the ri

Time:04-10

I need to make a link to the right of a span, and make that span overlined by clicking the link.

The main problem is that both link and span overlines, and I don't know how to fix it. The other problem is they can't be justified by width, as they appear to be together.

I tried to change beforeend attribute of insertAdjacentElement to afterend, but it makes link appear under every span, which is actually not what I want.

Thanks in advance!

let p = document.querySelectorAll('p');

p.forEach(node => {
  node.innerHTML = `<span>${node.textContent}</span>`;
})

for (let elem of p) {
  let a = document.createElement('a');
  a.href = '';
  a.innerHTML = 'cross';

  a.addEventListener('click', function(event) {
    event.preventDefault();
    elem.classList.toggle('overlined');
  })

  elem.insertAdjacentElement('beforeend', a);
}

CodePudding user response:

That's becasue you are applying the overlined class to the p element which also contains your cross link. Apply it to the span by using children[0] or firstChild of p.

I also suggest adding some css classes to your span and a tags so you can style them as you wish.

let p = document.querySelectorAll('p');

p.forEach(node => {
  node.innerHTML = `<span >${node.textContent}</span>`;
})

for (let elem of p) {
  let a = document.createElement('a');
  a.href = '';
  a.innerHTML = 'cross';
  a.classList.add("myLink");

  a.addEventListener('click', function(event) {
    event.preventDefault();
    elem.firstChild.classList.toggle('overlined');
  })

  elem.insertAdjacentElement('beforeend', a);
}
.overlined {
  text-decoration: line-through;
}

.mySpan {
  display: inline-block;
  margin-right: 10px;
  width: 50px;
}

.myLink {
  color: green;
  display: inline-block;
}
<p>test</p>
<p>test 2</p>

  • Related