简体   繁体   English

如果仅在DOM中呈现一个HTML相同的id元素,则多个

[英]Multiple HTML same id elements if only one is rendered in the DOM

Can you have multiple same id elements if only one is rendered in the dom? 如果仅在dom中呈现一个id元素,您是否可以有多个相同的id元素? For example in Laravel you can have: 例如,在Laravel中,您可以拥有:

 @if (Route::has('login'))
   @auth
     <h2 id='header'>Dashboard</h2>
 @else
     <h2 id='header'>Sign up</h2> 
   @endauth
 @endif

I realize multiple id on same elements is bad practice, but technically in a situation like this only one element would be rendered in the DOM, as far as browser is conserned, it only detects one of them, so would it have any bad effects regarding javascript etc..? 我意识到在同一个元素上使用多个id是不好的做法,但是从技术上讲,在这样的情况下,只有一个元素会在DOM中呈现,就浏览器而言,它只能检测到其中一个,因此对javascript等。? It can simplify css though. 它可以简化CSS。
I don't plan to use this in my projects, just curious. 我不打算在我的项目中使用它,只是出于好奇。

I would go this way : 我会这样:

@if (Route::has('login'))
  <h2 id="header">{{ Auth::check() ? 'Dashboard' : 'Sign up' }}</h2>
@endif

In any case having a class is better even for the css as the ID adds a much bigger weight on the element, for example if you want to override a css property you won't be able to achieve it by just adding a class. 无论如何,对于CSS来说,拥有一个类是更好的选择,因为ID会增加元素的权重,例如,如果您想覆盖一个CSS属性,那么仅通过添加一个类就无法实现。

An example for this will be: 一个例子是:

#header {
 font-size: 1.5rem;
}

later you want to override the css on just one header element and not on the other, adding a class to that element won't override the font-size of the element. 稍后,您只想在一个标头元素上覆盖css,而不是在另一个标头元素上覆盖css,则向该元素添加类将不会覆盖该元素的字体大小。 I hope I am clear with the example. 我希望我对这个例子很清楚。

So to summarize your code is okay, it will get only one element on the page with the ID when it get's rendered. 因此,总结您的代码是可以的,在呈现代码时,它只会在页面上获得一个具有ID的元素。

If only one "h2" of them will be rendered, it doesn't differ from writing only one of them due to your code, there's no way the two "h2" will be rendered in the DOM 如果只渲染其中一个“ h2”,则由于您的代码,与仅编写其中一个“ h2”没有什么不同,因此无法在DOM中渲染两个“ h2”

the only thing will cause a problem if any two elements were rendered in the DOM with the same ID 如果在DOM中使用相同的ID渲染了任何两个元素,则唯一的问题将导致问题

in that case, if you tried to select one of them or apply any js to them it will select the first element was rendered on the DOM 在这种情况下,如果您尝试选择其中一个或对它们应用任何js,它将选择在DOM上呈现的第一个元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM