javascript - How should I best search through a custom list generated dynamically based on id for a specific element? -


so, have scenario have list of div elements of class 'item', , want traverse through elements elements specific attribute.

example html:

<div>      <div class='item' data-id='bob123'>bob</div>     <div class='item' data-id='tedddd'>ted</div>     <div class='item' data-id='mikester'>mike</div>     <div class='item' data-id='joeyboy'>joe</div> </div> 

with list, current method of selecting specific element through dataset property, store person's id under data-id.

using jquery, have:

var specificelement = $('.item[data-id=(user id)]); 

then, perform operations on element such highlighting, showing , hiding.

now, dilemma whether efficient method of sifting through list, since heard accessing dataset slow.

should change html schema , store id different way (such using classlist)? hesitant on marking each id such user_bob123 since feel potentially create conflicts within rest of html, though allow access

document.getelementbyid('user_' + id); 

i open suggestions, , since selecting elements common part of application want sure efficiently possible.

there's no concept of dataset in html5. these data- attributes custom attributes. is, there's no additional overhead when retrieving elements using selector have other case, excepting when by id (i.e. document.getelementbyid), may optimized browser storing both ids , elements in hash table fast access.

btw, if want optimize access elements data-id, should able store references of these elements in object , access them using regular javascript functions:

// vanilla js!!  var items = [].slice.call(document.queryselectorall(".item[data-id]"))    .reduce(function(result, currentelement) {      result[currentelement.getattribute("data-id")] = $(currentelement);      return result;    }, {});    // access these elements id, , won't need query document  // anymore. accessing object properties faster selector:  var bob123element = items["bob123"];    settimeout(function() {    bob123element.hide();  }, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div>    <div class='item' data-id='bob123'>bob</div>    <div class='item' data-id='tedddd'>ted</div>    <div class='item' data-id='mikester'>mike</div>    <div class='item' data-id='joeyboy'>joe</div>  </div>


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -