Arthur0902
Arthur0902

Reputation: 209

How to find wether a specific DOM is exist or not inside a DIV by javascript/jquery?

I have a HTML structure like this:

<div id='list'>
  <table id='1'></table>
  <table id='2'></table>
  <table id='r'></table>
  //And more...
</div>

All the tables are added dynamic by other codes. Also their ID are generated dynamic.

I hope to know that, when I need to add a new table, how can I check the new table's ID is already existed in the list or not? That is , how to check if a id is in the div or not?

Thank you!

Upvotes: 2

Views: 193

Answers (2)

Ed Bayiates
Ed Bayiates

Reputation: 11210

Use the jQuery find() API to find an element within another. Documentation here. The find() API lets you select as $() does, but within a target as the OP wants. Note that find() also goes through all children of all levels, not just the direct children (grandchildren, great-grandchildren, etc.).

Working JSFiddle here showing this API which finds the target span by ID in one DIV but not in another.

Upvotes: 2

Amareswar
Amareswar

Reputation: 2064

$(#id).length > 0 means id already exists.

Upvotes: 1

Related Questions