开发者

How can I add a span between 2 spans?

On my page, I have multiple div with specified class which have 2 span elements. I want to check if the second element has a particular class, add new span object between the 2 span.

var allrtSp = $(".rtSp");
        for (i = 0; i < allrtSp.length; i++) {
            var cls= $(allrtSp[i]).next().attr('class');
            var newSpan;
 开发者_运维问答           if (cls != 'rtMinus' && cls != 'rtPlus')
            {
                $(allrtSp[i]).add('<span class="rtNoChild"></span>');
            }
        }

I used the above code, but this is not working.


Shouldn't you be using

$(allrtSp[i]).after('<span class="rtNoChild"></span>')

The code you have will add a new span as a child of allrtSp[i] as opposed to between it and the next span.


Try this

var secondSpan;
$(".rtSp").each(function(){
   lastSpan = $(this).find("span:last");
   if(lastSpan.hasClass("classNameToCheck")){
     lastSpan.before("<span  class='rtNoChild'>text</span>");
   }
});


Check with this code:-

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Jquery FROM CDN vs self host</title> 

    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js" type="text/javascript"></script>

</head>
<body>
<h1>Test</h1>

<div class="divcssclass">
<span>Test1</span>
<span class="particularClass">Test2</span>
</div>

<div class="divcssclass">
<span>Test3</span>
<span>Test4</span>
</div>

<div class="divcssclass">
<span>Test5</span>
<span class="particularClass">Test6</span>
</div>
<script type="text/javascript">
    $(document).ready(function () {
        $("div.divcssclass").each(function () {
            var secondSpan = $(this).find("span:nth-child(2)");
            //alert(secondSpan.hasClass("particularClass"));
            if (secondSpan.size() > 0 && secondSpan.hasClass("particularClass")) {
                secondSpan.before('<span> Test </span>');
            }
        });

    });
    </script>
</body>
</html>


Most concise I can think of:

$('div.rtSp span:nth-child(2).the_class').each(function() {
    $(this).before('<span class="rtNoChild">2</span>');
});

for the following HTML

<div class="rtSp">
    <span>1</span>
    <span class="the_class">3</span>
</div>

will produce

<div>
    <span>1</span>
    <span class="rtNoChild">2</span>
    <span class="the_class">3</span>
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜