开发者

remove div for same prefix id

开发者 https://www.devze.com 2023-03-06 00:55 出处:网络
There\'s a task i want to do, remove the divs with the same prefix. <div id=\"random-asadf12s\"></div>

There's a task i want to do, remove the divs with the same prefix.

<div id="random-asadf12s"></div>
<div id="random-afsdf123"></div>
<div id="random-xcvsd121"></div>
<div id="random-1edffxcx"></div>
<div id="random-56hgrgry"></div>
<div id="random-546fgfgh"></div>
<div id="random-gfh754yy"></div>
<div i开发者_开发技巧d="random-fghfghrt"></div>

those divs are generated by some js.

In jQuery, i can use jQuery("#id").remove(); to remove a certain element. but how can i do the same thing if i don't know the exact id of the element?


You could use the attribute starts with selector:

$('div[id^="random-"]').remove();

This is probably better as jQuery can directly pass this selector to querySelectorAll in the newer browsers (although I don't know if it actually does it).

Alternatively you can use the attribute contains prefix selector:

$('div[id|="random"]').remove();


Try this out:

$divs = $('div[id|="random"]').remove();

http://api.jquery.com/attribute-contains-prefix-selector/


you can use the Attribute Contains Selector

 $('div[id*="random-"]')

or the Attribute Starts With Selector

 $('div[id^="random-"]')


I think this should do the trick:

$("[id^=random-]").remove();


How about filter?

$('div').filter(function () { return /^random-/.test(this.id); })


You can use .filter() function (see fiddle: http://jsfiddle.net/VG5BP/):

(function(){
    $('#test').click(function(event){
        event.preventDefault();
        $("body > div").filter(function() {
            return $(this).attr('id').match(/^(random-)/);
        }).remove();
    });
})();

In place of "body > div" you add selector for elements you want to check and possibly delete some of them. Check fiddle, it works.

0

精彩评论

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