I’m very new to jQuery and i’m developing a plugin (for my own use) for setting DOM elements html() with content returned by an ajax call. Example:
<span id="a" class="scalar">?</span>
<span id="b" class="scalar">?</span>
<span id="c" class="scalar">?</span><!-- this will not be updated -->
If stats.php is going to return a JSON object like this: { a : 3, b : 7 } the resulting HTML would be (each object property will match an id among the selection on which the plugin was invoked):
<span id="a" class="scalar">3</span>
<span id="b" class="scalar">7</span>
<span id="c" class="scalar">?</span><!-- this will not be updated -->
This is the plugin invocation and definition. Question is: why find() can’t properly select the element to be updated?
<script type="text/javascript">
$(document).ready(function() {
$('.scalar').scalar({ url : '../REST/stats.php' });
});
</script>
(function($) {
$.fn.scalar = function(options) {
var opt = $.extend({
url : 'REST/stats.php',
type : 'POST',
context: this,
dataTypeString : 'json'
}, options);
$.ajax($.extend(opt, {
success : function(obj) {
for(k in obj) {
if(!obj.hasOwnProperty(k)) continue;
console.log(this.find('#' + k));
}
}
}));
return this.each();
};
})(jQuery);
Because
findlooks for descendant elements, and the elements you are looking for are not descendants (they are all siblings of each other). Usefilterinstead:thiswill be a jQuery object wrapping a set of DOM elements. Unless one or more of those elements contains a descendant element with theidyou are looking for withfind, it won’t work. You need to look at the elements themselves, which is whatfilterdoes.