简体   繁体   中英

Check if an HTML element with the same id exists

可以使用javascript完成吗?

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.

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
        } 
    }
}

Maybe (if I understand the question)

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

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

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