如何更改div子中的所有元素id

时间:2016-10-12 09:06:56

标签: javascript

我如何更改和添加内容到div子元素中的所有id,这些元素在他的第一个中有bi_。像这个例子:

<script>
    var opts = '1';
    $('.mm > #bi_name').attr('id', 'bi_name_'+opts);
    $('.mm > #bi_email').attr('id', 'bi_email_'+opts);
    $('.mm > #bi_expire').attr('id', 'bi_expire_'+opts);

    $('.ss > #bi_ohhh').attr('id', 'bi_ohhh_'+opts);
    $('.ss > #bi_bala').attr('id', 'bi_bala_'+opts);
    $('.ss > #bi_ola').attr('id', 'bi_ola_'+opts);

    .....

</script>

<div id="lol" class="mm">

    <!-----I want to change all id below----->

    <div id="profile"> 
                <div class="about text-center">
                    <h1 id="bi_name">Banned player name</h1>    //change and this id="bi_name" to id="bi_name_1"
                </div>
                <ul class="personal-info">
                    <li><label><i class="fa fa-envelope fa-fw fa-lg"></i> Email</label><span id="bi_email">EMAIL</span></li> //change and this id="bi_email" to id="bi_email_1"
                    <li><label><i class="fa fa-calendar fa-fw fa-lg"></i> Expire Time</label>
                        <span>
                            <a href="" id="bi_expire" data-original-title="Select Date of ban expire">EXPIRE TIME</a> //change and this id="bi_expire" to id="bi_expire_1"
                        </span>
                    </li>
                </ul>
    </div> 
    <div id="content" class="ss">
        .....
    </div> 
    <div id="gallery" class="gg">
        ....
    </div> 

    <!-----I want to change all id above----->

</div>

1 个答案:

答案 0 :(得分:1)

您可以使用Attribute Starts With Selector [name^=”value”]使用目标所有元素,然后使用.attr(attributeName, fn)设置id

var opts = '1';
$('.mm [id^=bi_]').attr('id', function(_, val){
    return val + '_' + opts;
});