单击文本时删除<span>

时间:2016-10-27 07:15:20

标签: jquery

我有以下HTML:

<span class="deleted typo" id="typo1" contenteditable="false"> innovation via workplace diversity</span>

当我单击文本本身时,我需要删除<span>元素而不删除内部文本,并且它只需要在此元素上,而不是具有相同类的其他元素。这有可能与jQuery?

6 个答案:

答案 0 :(得分:3)

&#13;
&#13;
$('#typo1').click(function() {

  $(this).contents().unwrap("<span></span>");

})
&#13;
.deleted{color:red}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="deleted typo" id="typo1" contenteditable="false"> innovation via workplace diversity</span>
&#13;
&#13;
&#13;

.contents().unwrap()

一起使用

.contents()

  

描述:获取匹配元素集中每个元素的子元素,包括文本和注释节点。

.unwrap()

  

描述:从DOM中删除匹配元素集的父节点,将匹配的元素留在原位。

答案 1 :(得分:0)

使用jquery

尝试此操作
<script    src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<script>

 $(document).ready(function(){
        $("#typo1").click(function(){
            $(this).remove();
        });
});

</script>

答案 2 :(得分:0)

 <span class="deleted typo" id="typo1" contenteditable="false"> <p>innovation via workplace diversity</p></span>


 $("#typo1").click(function(){
        $("p").unwrap();
 });

答案 3 :(得分:0)

只是为了娱乐和教学方式,没有任何lib,这是一个纯粹的JavaScript解决方案

&#13;
&#13;
document.getElementById('typo1').addEventListener('click', function() {
  var mySpan = document.getElementById('typo1');
  var parentNode = mySpan.parentNode ;
  while (mySpan.firstChild) parentNode.insertBefore(mySpan.firstChild, mySpan);
  mySpan.parentNode.removeChild(mySpan);

});
&#13;
<span class="deleted typo" id="typo1" contenteditable="false"> innovation via workplace diversity</span>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

你需要的是:

$('#typo1').click(function() {

   // get the text
   var t = $(this).text();

   // get the parent to add the text after removing the span
   var p = $(this).parent()

   // remove the span
   $(this).remove();

   // set the text back to parent
   p.text(t);

   // if the parent has more controls you may have to append
   // p.append(t);

});

https://jsfiddle.net/tedmanowar/ykb1px05/

答案 5 :(得分:0)

这是我发现的。 .unwrap()将无效,因为它会删除选择器的父元素,而不是文本节点周围的元素。您必须将this替换为childNodes

$(document).ready(function(){
    $(".typo").click(function(){
        $(this).replaceWith(this.childNodes);
    });
});
相关问题