简体   繁体   中英

error selecting div element with a particular id - beginner at jQuery, javascript

I am playing around with selecting elements in the DOM using jQuery, and I tried the following:

$(document).ready(function() {

      $("a").toggle(function(){
        $("div[@id=SomeID]").hide('slow');
        },function(){
        $("div[@id=SomeID]").show('fast');
       });

});

And in the html source, I do have this section:

<div id="SomeID">

      <!-- div code -->

</div>

However, when I click on an anchor tag I get the following error:

Syntax error, unrecognized expression: div[@id=SomeID]

Any ideas as to what is going wrong here? I'm a beginner at jQuery and javaScript, so would appreciate any help.

To select an element by its id in jQuery, use the same syntax as in CSS:

$('#someID');

To use the attribute-equals selector format then use:

$('div[id="someID"]');

References:

You are using the Wrong selector.. Id has to be prepended with a #

These are valid

$("#SomeID").hide('slow'); //  element with id SomeID , can be any element
$("div#SomeID").hide('slow'); //  Div with id SomeID
$("div[id=SomeID]").hide('slow'); //  Div with id SomeID
$("div[id^=SomeID]").hide('slow'); //  Div id that starts with SomeID
$("div[id*=SomeID]").hide('slow'); //  Div id that has SomeID in its id attribute
$("div[id=SomeID]").hide('slow'); //  Div id that ends with SomeID

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