For example, I have the html block:
<div class="span3">
<div class="firstDiv"></div>
</div>
<div class="span3">
<div class="secondDiv"></div>
</div>
Replicas of this html block can be inserted using javascript, so I have a large number of these blocks one after another.
I’d like to hear perspective on whether putting id’s on all of these elements in order to work with them is a standard/efficient way to do things. I have a good way to put unique ids with matching suffixes on generated elements, like:
...
<div class="span3">
<div id="firstDiv_154 class="firstDiv""></div>
</div>
<div class="span3">
<div id="secondDiv_154 class="secondDiv""></div>
</div>
<div class="span3">
<div id="firstDiv_155 class="firstDiv""></div>
</div>
<div class="span3">
<div id="secondDiv_155" class="secondDiv"></div>
</div>
...
Then as a general rule, to do something to the secondDiv when I click the firstDiv in the set I could just do:
$('.firstDiv').on ('click', function(evt) {
var idToFind = $(evt.target).attr('id').replace(/firstDiv/, /#secondDiv/)
var $secondDiv = $(idToFind);
// do something with $secondDiv
});
Are there more efficient ways to use id’s?
If not using id’s, I could use jQuery:
If I want to find the second element from the first:
$('.firstDiv').parent().next().children()
which would break if I rearranged elements too much,
or
$('.firstDiv').closest('.span3').find('.secondDiv')
which would be more robust, but is likely more resource intensive than the first jQuery method.
Which of all of these methods would you (experienced web devs, please) recommend?
It depends on what you’re trying to accomplish. If you need a way to uniquely identify an element and there is no other way in your current setup to do so, then unique id’s is a good way to go.