用其他字符串替换nextSibling

时间:2016-12-13 20:14:21

标签: javascript jquery nextsibling

我有以下span元素:

<div class="text" contenteditable="true" id="example">
   <div class="outside">Type here <span class="inside"> please</span>.</div>
   <div class="outside">Name here <span class="inside"> first </span>name</div>
</div>

使用以下js函数,我可以得到</span></div>之间的长度:

$('span.inside').each(function() {               
    var sphs = $(this).get(0).nextSibling;
    var len = sphs.length;

    //If the length is less than 2
    if(len < 2){
        // i want to replace it with another words like "thanks."   

       }
 })

如果长度小于8,那么我想将其替换为其他字词或字符串(例如,thanks.)IN BETWEEN </span></div>(请参阅“谢谢“安置”。

<div class="text" contenteditable="true" id="example">
   <div class="outside">Type here <span class="inside"> please</span>thanks.</div>
</div>

我如何用另一个字符串替换它?

修改

请注意,我使用的是.each,因为可能存在多个具有相同类名的span元素。在第一行中,只有一个句点(</span>.</div>),因此它满足条件并将被替换为另一个单词(在本例中为“thanks”)。

在第二行(</span>name</div>)中,长度大于2,因此不会被替换。

我希望这能澄清它。

<div class="text" contenteditable="true" id="example">
   <div class="outside">Type here <span class="inside"> please</span>.</div>
   <div class="outside">Name here <span class="inside"> first </span>name</div>
</div>

......将成为......

<div class="text" contenteditable="true" id="example">
   <div class="outside">Type here <span class="inside"> please</span> thanks.</div>
   <div class="outside">Name here <span class="inside"> first </span>name</div>
</div>

2 个答案:

答案 0 :(得分:1)

$('span.inside').each(function() {               
    var sphs = $(this).get(0).nextSibling;
    var len = sphs.length;

    //If the length is less than 2
    if(len < 2){
        // DOM method:
        sphs.textContent = ' Thanks.';
        // jQuery method:
        $(this).parent().get(0).childNodes[2].textContent = ' Thanks.';
    }
 })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="text" contenteditable="true" id="example">
   <div class="outside">Type here <span class="inside"> please</span>.</div>
   <div class="outside">Type here <span class="inside"> please</span> ok?</div>
</div>

或者试试这里 https://jsfiddle.net/8pa4akzh/3/

答案 1 :(得分:0)

添加额外(空)范围并进行设置。它就像设置范围的text()一样简单。

<强> HTML:

<div class="text" contenteditable="true" id="example">
    <div class="outside">Type here <span class="inside"> please</span><span id="extra"></span></div>
</div>

<强> JS:

   //If the length is less than 2
   if(len < 2){
        $('span#extra').text("thanks.");
   }