user3633186
user3633186

Reputation: 1540

jQuery if two elements exists delete the first

I want to check if two elements exist. One has the #one the other #two. And if both exists i want to remove #one.

If only #one exist do nothing. If only #two exist do nothing. If #one and #two exist delete #one.

Could someone help me to geht this thing working ?

if($("#one") AND $("#two")) {
$("#one").remove();
}

My little snippet does not wirk

Upvotes: 3

Views: 1143

Answers (2)

Adil
Adil

Reputation: 148140

You need to use && instead of AND and length to check if element exists. JQuery selector returns the object even the selector returns No element. So using .length will return zero when no element is return by selector and greater than zero when element(s) are returned by selector.

if($("#one").length && $("#two").length) {
   $("#one").remove();
}

Upvotes: 7

Andrew Shepherd
Andrew Shepherd

Reputation: 45252

if ( $("#one, #two").length === 2 ) {
   $("#one").remove();
}

Upvotes: 6

Related Questions