Which is the better approach for performance: querying on parent selectors or appending selectors to all children?

I currently have 2 mirror sections within my DOM, one for delivery and another for pickup. Both of these sections contain identical content structures. Here's an example:

<div class="main-section">
  <div class="description-content">
    <p><span class="to-emphasize"></span></p>
  </div>
  <div class="field-content">
    <input type="text" name="address"></input>
  </div>
  <div class="table-content">
    <table>
      <thead>
        <tr>
          <td></td>
        </tr>
      </thead>
    </table>
  </div>
</div>

The question I have is regarding the efficiency of jQuery targeting and retargeting in situations like this. Which strategy would be more efficient? Here are two options to consider:

Strategy A: Add delivery/pickup selector to parent and query on parent.

<div class="main-section" data-type="delivery">
  <div class="description-content">
    <p><span class="to-emphasize"></span></p>
  </div>
  <div class="field-content">
    <input type="text" name="address"></input>
  </div>
  <div class="table-content">
    <table>
      <thead>
        <tr>
          <td></td>
        </tr>
      </thead>
    </table>
  </div>
</div>

// jQuery code example
$(".main-section[data-type='delivery'] input[name='address']").val("new value")
$(".main-section[data-type='delivery'] .to-emphasize").empty()
$(".main-section[data-type='delivery'] .to-emphasize").append("new value")
delivery_or_pickup = $(this).parents(".main-section").data("type")
$(".main-section[data-type='"+delivery_or_pickup+"']").hide()

Strategy B: Add delivery/pickup selector to all children that need querying.

<div class="main-section" data-type="delivery">
  <div class="description-content" data-type="delivery">
    <p><span class="to-emphasize" data-type="delivery"></span></p>
  </div>
  <div class="field-content" data-type="delivery">
    <input type="text" name="address" data-type="delivery"></input>
  </div>
  <div class="table-content" data-type="delivery">
    <table>
      <thead>
        <tr>
          <td></td>
        </tr>
      </thead>
    </table>
  </div>
</div>

// jQuery code example
$("input[name='address'][data-type='delivery']").val("new value")
$(".to-emphasize[data-type='delivery']").empty()
$(".to-emphasize[data-type='delivery']").append("new value")
delivery_or_pickup = $(this).data("type")
$(".main-section[data-type='"+delivery_or_pickup+"']").hide()

Answer №1

The ideal solution for this scenario will ultimately be determined by the overall context of your code, as there are valid arguments for both approaches. If your code involves a significant amount of targeted elements, then I would suggest opting for the second option where you assign selectors to specific elements for two key reasons:

1. Reduction in Typing - Assign concise IDs to inputs that require frequent querying, such as #name, to minimize the number of characters needed each time they are accessed.

2. Enhanced Processing Efficiency and Speed - By assigning unique IDs to each input and storing them in variables, you can reduce the frequency of DOM look-ups performed by jQuery, thereby improving processing efficiency.

var name = $('#name');

Adhering to this practice is particularly beneficial when dealing with repetitive lookup of the same DOM elements throughout the codebase. This approach not only optimizes performance but also enhances code readability. For instance, the following code:

$("input[name='address'][data-type='delivery']").val("new value");

can be simplified to:

address.val("new value");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Sequelize will pause and wait for the loop to finish before executing the

As someone with a background in PHP, I'm finding the concept of callbacks a bit challenging to grasp. Essentially, I need to retrieve some rows and then iterate through them to compare against another model (in a different database). However, I want ...

Unable to directly assign a variable within the subscribe() function

My goal is to fetch a single row from the database and display its information on my webpage. However, I've encountered an issue with the asynchronous nature of subscription, which prevents immediate execution and access to the data. Upon running the ...

Simple HTML and CSS exercise for beginners to grasp the concept

I'm looking to modify the layout of a specific webpage at based on the following instructions: First, insert this link within the <head> <link rel="stylesheet" href="https://trafficbalance.io/static/css/sdk/sdk.css"> -next, add th ...

Combining multer, CSRF protection, and express-validator in a Node.js environment

Within my node.js application, I am utilizing an ejs form that consists of text input fields in need of validation by express-validator, an image file managed by multer, and a hidden input housing a CSRF token (a token present in all other forms within the ...

Design featuring a fixed top row and a scrollable bottom row

I need to divide a div container into two vertical sections, one occupying 60% of the space and the other 40%. The top div (60%) should always be visible, while the bottom div (40%) should be scrollable if it exceeds its limit. I have tried different app ...

Is it acceptable to use JavaScript files in the pages directory in NEXTJS13, or is it strongly advised to only use TypeScript files in the most recent version?

In the previous iterations of nextJS, there were JavaScript files in the app directory; however, in the most recent version, TypeScript files have taken their place. Is it still possible to begin development using JavaScript? I am working on creating an a ...

The res.sendFile() function quickly delivers a 204 no content response

Currently, I am facing an issue with using Express' sendFile() function to send an image. The function does not seem to read my file at all and instead returns a 204 no-content response. Below is the code for my function/endpoint: @httpGet('/pri ...

Setting Up AdminLTE Using Bower

Recently, I decided to incorporate the Admin LTE Template into my Laravel project. I diligently followed the guidelines outlined here As soon as I entered the command: bower install admin-lte The installation process seemed to start, but then the ...

Is there a way for me to convert this JSON object back into a string?

Presently, I possess this specific JSON object "name": "Luke Skywalker", "height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair", "eye_color": "blue", "birth_year": "19BBY", "homeworld": "Tatooine", "films": [ "A N ...

Tips for increasing the width of a button within an HTML table heading

I'm attempting to make a button within a table <th> expand to the full width and height of the header column, even if a table cell in the same column is larger than the text. If I set the width to 100% in CSS, the button ends up matching the siz ...

Tips for creating canvas drawings in GWT

Here's a simple jQuery code to draw a triangle in a canvas element that is 40 by 40: var context1 = $("#arrow_left").get(0).getContext('2d'); context1.beginPath(); context1.moveTo(25,0); context1.lineTo(0,20); context1.lineTo(25,40); contex ...

Transform JSON query conditions into MongoDB/Mongoose commands

I'm currently developing an application using Angular 8 on the front end and NodeJS 12 with MongoDB 4 / Mongoose 5 on the back end. Using the Angular query builder module, I have generated a query in JSON format. This JSON object will be sent to the ...

showcasing products from database with the help of Angular 12

Here are the files related to the item: Item file And here is the component file: Component file Lastly, this is the data service file: Data Service file However, issues arise when testing the code with console log statements as it indicates that the ...

Ways to extract a specific value from a geojson object using the key name

After making a call to the back-end, I retrieved the below geojson data in the 'data' object. However, when trying to access the values of the 'type' and 'features' keys within the geojson, I encountered difficulties. data["g ...

Tips for maintaining video height consistency while adjusting its attributes

When you click on a button, the video's poster and src attributes change. However, after clicking, the video height briefly becomes 0, causing an unsightly effect on the entire page. How can this be avoided? Please note - lorem.mp4 and ipsum.mp4 hav ...

Dynamic content is loaded on the page using AJAX before refreshing to retrieve new

I am using the FullPage.js plugin and attempting to enable navigation between pages using AJAX. While using .load();, I am able to retrieve the desired page. However, it seems that I need to reload fullpage.js since the loaded page is not active and the s ...

The scale configuration for scale: x is not valid for creating a time scale chart using chart.js

I am currently utilizing VueJS and attempting to integrate a time scale chart using Chart.js. However, I encountered the following error: Invalid scale configuration for scale: x Below is my configuration : First, I have a component named Chart.vue with ...

What is the best way to include multiple views in a main HTML template in Angular?

Is there a way to load two HTML files into a base HTML file? Essentially, I have a base HTML file with a header and content view, and I want to load different HTML files into each of them. Here is the base HTML file structure: <div class="container"> ...

Every time I attempt to launch my Discord bot, I encounter an error message stating "ReferenceError: client is not defined." This issue is preventing my bot from starting up successfully

My setup includes the following code: const fs = require('fs'); client.commands = a new Discord Collection(); const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js')); for(const file of com ...

Is it necessary to compile Jade templates only once?

I'm new to exploring jade in conjunction with express.js and I'm on a quest to fully understand jade. Here's my query: Express mentions caching jade in production - but how exactly does this process unfold? Given that the output is continge ...