简体   繁体   中英

javascript id vs. class selector nested

If I have following code

<div id="container1">
   <div id="elementcontainer1" class="elementType"></div>
</div>
<div id="container2">
   <div id="elementcontainer2" class="elementType"></div>
</div>

To find element that belongs to specific container, I can select first correct container and then inside it correct type by class:

document.getElementById(containerId).getElementsByClassName("elementType")

or alternatively I can specify in the element which container it belongs to:

document.getElementById("element" + containerId)

The latter would be faster as it goes straight to the right id, but on the other hand I'd need to define different id for each although the components are otherwise the same.

What aspects I should consider when choosing which one to use?

First, think about how much are you gonna be using that and on how large DOM. Cause if you put like 100k elements in DOM it's gonna lag from rendering no matter your selectors. For example, if it's gonna be done once or twice and only bring lag of around 1-5 X 100ms it's not all that important. If by comparison you are going to use it on every filter change and you expect users to reconfigure filters every couple of seconds and faster then lag will matter.

Other than that I believe you could pick whichever you have the least time invested. If you can be positive 1st won't be broken by future upgrades go with it.

On the other hand, if you got an easy way of enumerating each end every one of them with unique id I would always prefer to target directly, faster, easier to debug, less likely to become broken with updates.

TL DR: unique Id if it's not a massive time to invest in doing so, otherwise the other method.

I once had a similar issue and i used the latter code. Because i knew the ID's of the elements i was using.

The back end logic would iterate and print all the rows also with buttons attached to the row with the value/id as same as the row.

So i used the code

document.getElementById("elementContainer" + containerId);

As i knew the indexing of the elements.

If that isn't your case, you can use the LOC

document.getElementById(containerId).getElementsByClassName("elementType")

To access your elements, it would really be upto you which code do you want to use. Meanwhile, the speed difference would almost be negligible for most use cases, as @CBroe stated in the comments.

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