clonebaby59
clonebaby59

Reputation: 187

Jquery search througha class check if it has a certain id

hey I want to search through a class and check if that class contains a certain id. Do I have to use .each? if i do i dont know how to exactly use it, could someone show me how to use it in this context, any help is appreciated

  if(id == $('.people').attr('id'))
  {
       alert("person exists");
  }

Upvotes: 1

Views: 91

Answers (4)

AlexKempton
AlexKempton

Reputation: 1698

One solution would be to use a simple selector, and check if that element exists.

if ($('.people#'+id).length())  { //Checking length() checks if element exists
    alert("person exists");
}

Upvotes: 0

Paul
Paul

Reputation: 141839

Since an id can only be used once you can instead search for the element with that id and check if it has the class. That will be much faster:

$('#the-id').hasClass('the-class');

Upvotes: 0

Bassam Mehanni
Bassam Mehanni

Reputation: 14944

since ids should not be used more than once, you simply can do:

if($('#' + id + '.people').length >= 1)
  alert('person exists'); 

Upvotes: 3

David Hedlund
David Hedlund

Reputation: 129792

You can search for an ID with

$('#my-id')

In your case,

$('#' + id)

You can check if the result is empty by testing for length:

if($('#'+id).length == 0)

To verify that it is a .person element that has the given ID, you could test

if($('.person#'+id).length > 0) {
    alert('person exists');
}

Upvotes: 3

Related Questions