Как добавить в конец каждого абзаца ссылку, по клику на которую текст абзаца будет перечеркиваться

Рейтинг: -5Ответов: 3Опубликовано: 04.07.2023

Необходимо добавить в конец каждого абзаца ссылку, по клику на которую текст абзаца будет перечеркиваться, а ссылка нет.

let ps = document.querySelectorAll('p')

for (let p of ps) {

  p.innerHTML = '<span>' + p.innerHTML + '</span>';
  let remove = document.createElement('a');
  remove.href = '#';
  remove.textContent = 'remove';
  p.appendChild(remove)

  let spans = document.querySelectorAll('span')

  for (let span of spans) {
    remove.addEventListener('click', function() {
      span.classList.add('colored')
    })
  }
}
.colored {
  text-decoration: line-through;
}
<p>text1</p>
<p>text2</p>
<p>text3</p>

Ответы

▲ 0

Измените эту часть, убрав переход по ссылке и следующее за ним обновление страницы методом preventDefault.

for (let span of spans) {
    cross.addEventListener("click", function (event) {
        span.classList.add("stiling");
        event.preventDefault();
    });
}
▲ 0
        let ps = document.querySelectorAll('p');
        for(let p of ps){
            let a=document.createElement('a');
            a.href='#';
            a.textContent='  remove'; 
            let span=document.createElement('span');
            span.textContent=p.textContent;
            p.textContent='';
            p.appendChild(span);  
            p.appendChild(a);
            a.addEventListener('click', function fn(){
              
                span.style.textDecoration='line-through';
            })
          }      
▲ -1

Вот так это можно реализовать

<!DOCTYPE html>
<html lang="ru">
<head>
  <meta charset="utf-8">
  <title>href</title>
  <style type="text/css">
    p#p1 {
      text-decoration: none;
    }
    p#p2 {
      text-decoration: none;
    }
    p#p3 {
      text-decoration: none;
    }
    p {
      display: inline;
    }
  </style>
</head>
<body>
  <p id="p1">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
  tempor incididunt ut labore et dolore magna aliqua.</p>
  <a href="#">href</a><br>
  <p id="p2">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
  tempor incididunt ut labore et dolore magna aliqua.</p>
  <a href="#">href</a><br>
  <p id="p3">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
  tempor incididunt ut labore et dolore magna aliqua.</p>
  <a href="#">href</a>
  <script type="text/javascript">
    function myFunction () {
      document.getElementById("p1").style.textDecorationLine = "line-through"
    }
    function myFunction2 () {
      document.getElementById("p2").style.textDecorationLine = "line-through"
    }
    function myFunction3 () {
      document.getElementById("p3").style.textDecorationLine = "line-through"
    }
  </script>
</body>
</html>