最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery doesn't apply hide() to all of the divs with the same ID - Stack Overflow

programmeradmin5浏览0评论

I'm making a site, and the html is displayed through php with data fetched from a database. I have a foreach() function, so all of the things displayed have the same DIV ID's. It ends up being like 4 DIVs with the same ID (#content), so the PHP works fine, but I have a jQuery script and when I call the jQuery("#content").hide(); it only hides ONE of the DIV's not all of them, and I want it to hide all of them. Is there something else I have to do? Thanks.

I'm making a site, and the html is displayed through php with data fetched from a database. I have a foreach() function, so all of the things displayed have the same DIV ID's. It ends up being like 4 DIVs with the same ID (#content), so the PHP works fine, but I have a jQuery script and when I call the jQuery("#content").hide(); it only hides ONE of the DIV's not all of them, and I want it to hide all of them. Is there something else I have to do? Thanks.

Share Improve this question asked Nov 25, 2011 at 20:59 SupraSupra 2301 gold badge3 silver badges7 bronze badges 2
  • 1 some references: html4 This attribute assigns a name to an element. This name must be unique in a document. - html5 The id attribute specifies its element's unique identifier (ID). – Yoshi Commented Nov 25, 2011 at 21:03
  • For debugging purpose, you should test your pages in an HTML validator like validator.w3 (or install an extension like the Web Developer Toolbar in Firefox or an equivalent one in Chrome; the entry Tools/Validate HTML will submit your page to the validator). A valid code can automagically solve problems like this one. – FelipeAls Commented Nov 25, 2011 at 21:15
Add a ment  | 

4 Answers 4

Reset to default 6

You should use a class (.class_name), not an id--only one DOM element may have a given ID, otherwise it's invalid HTML. It's reasonable for an ID selector to return only a single element.

IDs on elements on a page should be unique. So every HTML tag you specify should have a different ID. If you want to hide all of a certain element, it might be suitable to add a class to the elements you wish to hide?

e.g.

<div class="divToHide">Content...</div>
<div class="divToHide">Content...</div>
<div class="divToHide">Content...</div>

Then your jquery would be:

$(".divToHide").hide();

That's simply because you cannot have more than one element with a specified ID. IDs are and must be unique. Only one single element with the same element may exist in a DOM.

Failing to follow this rule may result in broken scripts and other horrors.

You can use classes for this purpose.

an ID can only be used ONCE in HTML! because its a id and a id should always be Unique

发布评论

评论列表(0)

  1. 暂无评论