1

Using LESS CSS I was able to restrict entire stylesheets to acting on a specific div element. I would like to restrict entire javascript files to a specific div element on my page.

For example, a js file that is bootstrapped at the head of the page has code the manipulates table elements in the DOM. It does its job but also does ALL table elements on the page not the one specific one I wanted. Now the practical soultion is to change all ofthe respective jquery selectors to a more specific identifier. I know that. But there is mountains upon mountains of code and that is not feasible to do.

Is there a way to restrict javascript/jquery code to a specific div?

I want to avoid using iframes also.

Thanks.

2 Answers 2

1

You're able to check for elements if (jQuery('#element').html() !== null).

In this case i'm looking if #element is present in the dom. If it returns true i'am loading my plugin via ajax.

if (jQuery('#element').html() !== null) {
    jQuery.ajax({
        url: '../assets/js/plugins/myplugin.js',
        type: 'GET',
        dataType: 'script',
        cache: true,
        success: function(data, textStatus, xhr) {
            // Do whatever you want
        }
    });
}

But if you have multiple similar elements you can't be specific without to change your selector. Maybe you can deal width the index (position in DOM) of an element.

$("div:eq(2)") //get third div
Sign up to request clarification or add additional context in comments.

Comments

1

You can do something like this

In jQuery

var $div = function(sel) {
  $(sel, YOUR_DIV);
}

And after, instead of using $('selector') you can use $div('selector').

Comments

Your Answer

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