简体   繁体   中英

how to remove an array of div's with the same id using ajax?

I am echoing an array in php:

foreach ($array as $print) {

$var = $print['var'];   

<div id=post>echo $var;</div>

}

I have a function that removes this div if a user posts a new comment:

$("#post").remove();

However this will only remove 1 div with the id=post, I need to remove all of them, Is there a way to do this?

First of all, there is never a case where it makes sense to use duplicate id's on an html page. It's invalid, and no one should ever do it.

that said, you can solve this by using the attribute equals selector if you must use duplicate id's (which again, makes no sense.)

$('[id="post"]').remove();

The better solution of course would be to NOT use duplicate ID's, and instead use a selector based on whatever alternative you use.

So you should use class instead of id .

foreach ($array as $print) {
    $var = $print['var'];
    echo '<div class="post">'.$var.'</div>';
}

To remove all the elements by post class

$(".post").remove();

As mentioned ID's need to be unique, instead use classes.

<div class='post'>echo $var;</div>

And then

$(".post").remove();

Use class instead of id.

foreach ($array as $print) {
   $var = $print['var'];   
   echo "<div class='post'>".$var."</div>";
}

$(".post").remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM