0

Im trying to modify an object resulting from $('#some_id'), and everything seems to work fine, but when I ask back for my modified object it has no changes at all.

$('#log_container').log
undefined
$('#log_container').log = {}
Object {}
$('#log_container').log
undefined

Why $('#log_container').log is undefined instead of what I explicitly assign in the previous line?

2 Answers 2

1

Because jQuery('some-selector') returns a new object every single time it is invoked:

function whatHappens(selector) {
  return {
    magic: 'here'
  }
}

whatHappens('when').log  // undefined
var result = whatHappens('when');
result.log = {};
var result2 = whatHappens('when');
result === result2  // false
result.log   // {}
result2.log  // undefined

If you need some data to always be available on the object you can:

  • Use the data method to set the data on the DOM node:

    $('#log_container').data('log', {});
    $('#log_container').data('log');
    
  • Store a reference to the jQuery collection:

    var $logContainer = $('#log_container');
    $logContainer.log = {};
    $logContainer.log;  // {}
    
  • Update the returned jQuery collection's [[Prototype]] (jQuery.prototype, commonly referred to by it's alias, jQuery.fn) to add the data / methods (this makes the data available to all jQuery collections, past, present and future):

    jQuery.fn.log = function yourLoggingMethod() {
      // Available on all jQuery collections now
      // Shared state - don't put things like {} or []
      // on here unless you intend to have a mutable "global".
    };
    

    Then you can just create collections as normal:

    var $logContainer = $('#log_container');
    $logContainer.log  // function yourLoggingMethod
    
Sign up to request clarification or add additional context in comments.

Comments

0

Every time you run $('#log_container') it creates a new jQuery object.

If you want to specifically modify a jquery object for some reason (which you probably should not; there are much better alternatives), assign it to a variable; then modify and use that variable;

var test = $('#log_container');
test.log = {};
console.log(test.log);

1 Comment

This is a half-answer: "There are much better alternatives". Please provide a couple examples and why you think they are better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.