Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
jQuery change multiple attributes or replace entire html

I was wondering if it were more efficient/faster to change multiple attributes with jQuery or to just change replace all the html in one go. This is the code i am using at the moment.

// shows the table and changes the image to up
showTable = function(tableId){
    $('#img' + tableId).attr("src", images["up"]).attr("alt", "Hide Table").attr("title", "Hide Table");
    $('#' + tableId).fadeIn(250);
}

or would this be faster?

// shows the table and changes the image to up
showTable = function(tableId){
    $('#img' + tableId).replaceWith('some html');
    $('#' + tableId).fadeIn(250);
}
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

$('#greatphoto').attr({
  alt: 'Beijing Brush Seller',
  title: 'photo by Kelly Clark'
});

Example taken from jQuery Documentation.

over 4 years ago · Santiago Trujillo Report

0

Given that you're taking a quarter of a second to fade in the result and this isn't a tight loop, you're not going to notice any performance difference between the two. As yan.kun points out, you can make the code a bit more concise by using the multi-set (map) version of attr, but with three attributes not in a tight loop, it's not going to make a speed difference. (If it were, I'd avoid calling attr entirely and use the element's own reflected properties — src, alt, and title are all reflected.)

Having said that, there are other reasons to update elements rather than replace them. For instance, if you have any handlers attached to the elements, if you update the elements' attributes, the handlers remain attached; if you replace the elements, the handlers aren't attached (because they were attached to the old ones). Replacing elements also causes reflow, which can be significant (or not) depending on your DOM structure.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!