'Force Limit jQuery Selectors Only On Portions of the Page
I'm going out on a limb here but I thought I'd ask...
Let's say I have a ton of plugin initializations on my page like
$('.my-element').somejqueryplugin();
and I want to use AJAX to reload part of the DOM on the page.
I need to re-initialize all my plugins for the newly loaded DOM
But...that would cause issues since for DOM that didn't get reloaded I'd be re-initializing the plugins which would cause errors.
I know your standard ways around this (using more specific selectors or destroying the plugins before initialization) - but I'm looking to see if there's any trick I can use without modifying the selectors (or anything else) on existing JS.
Can anyone think of any cool hacks for this?
Solution 1:[1]
This can be done by passing a second parameter to the jQuery selector which is the context to which the first selector will be applied. Given the following HTML snippet
<div>
<p> Regular page stuff</p>
<div id="ajax-container"></div>
</div>
after your ajax call populates the div#ajax-container you can execute code on only the ajax added DOM elements with
$('.my-element', '#ajax-container').somejqueryplugin();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | schmolly159 |
