Sussagittikasusa
Sussagittikasusa

Reputation: 2581

Check if an HTML element with the same id exists

Can this be done using javascript?

Upvotes: 3

Views: 6412

Answers (5)

koula
koula

Reputation: 41

Also, in order to print all duplicates:

var elems = document.getElementsByTagName('*');
var num = elems.length;
var ids = [ ];
for(i=0; i<num; i++ ) {
    var id = elems[i].getAttribute('id');
    if(id != null) {
        if(ids.indexOf(id) >=0 ) {
            console.debug(id); // found in table
        } else {
            ids.push(id); // new id found, add it to array
        } 
    }
}

Upvotes: 3

Free Consulting
Free Consulting

Reputation: 4402

Yes it is. iterate thru document.getElementsByTagName('*'), use element.getAttribute('id')

Upvotes: 0

Skilldrick
Skilldrick

Reputation: 70849

If you're trying to find out if more than one element share one id, with jQuery you could do $('[id=blah]').length - that will return a count of all elements where the id is equal to 'blah'. See the fiddle. If it's greater than 1 then you have a duplicate id.

Edit: I've tested this in Chrome, FF and IE6, and all of them show that there are two elements with the same id. I agree that it's really bad form to have more than one element share an id, but this code does work.

Upvotes: 10

Thilo
Thilo

Reputation: 262524

Maybe (if I understand the question)

if (document.getElementById('theId')) {
}

Upvotes: 3

ceth
ceth

Reputation: 45295

if(!document.getElementById('search')) { return; }

Upvotes: 0

Related Questions