JohnG
JohnG

Reputation: 497

Using jQuery to change CSS of elements added into DOM

I'm trying to use jQuery to change the CSS properties of jQuery Validation plugin's error labels.

This is basically because I use jQuery equations to create responsive font-size, rather than native vw or em units via CSS. Normally works beautifully.

However, because the label is not initially in the DOM, I can't target it using a $(document).ready(function): although it works on $(window).resize(function).

So what function should I be using to change elements as they are loaded into the DOM?

Upvotes: 0

Views: 59

Answers (3)

JohnG
JohnG

Reputation: 497

Thanks everybody. In the end I used something from the MutationObserver discussion that HES_Xenon links to above: a jQuery Initialise plug-in based on the MutationObserver - basically because it used less code.

Upvotes: 0

gustavohenke
gustavohenke

Reputation: 41440

You should use the MutationObserver API, which will trigger a listener function as soon as the DOM of the specified element changes, so you're able to make sure your elements have the right CSS without triggering resize event.

Here's some example:

$(document).ready(function () {
    var observer = new MutationObserver(function ( mutations ) {
        var elements = mutations.reduce(function ( elements, mutation ) {
            return elements.concat( mutation.addedNodes );
        }, [] );

        // .filter() makes sure you only manipulate mutated elements that match your selector
        resizeFonts( $( elements ).filter( ".selector" ) );
    });
    observer.observe( $(".parent-element")[ 0 ], {
        childList: true,
        subtree: true
    });

    $( window ).resize(function () {
        resizeFonts( $( ".selector" ) );
    });
});

function resizeFonts ( elements ) {
    elements.css( "font-size", amazingNewFontSize );
}

Please note, however, that MutationObservers may not work in all browsers.
I based my example on this answer, which includes further code to make it work in older browsers.

Upvotes: 0

HES_Xenon
HES_Xenon

Reputation: 103

Well, maybe mutation observers could help? Found out about these nice things before I started using angular a few months ago, here's a post that might help

Detect changes in the DOM

--amend Watch the parent element, check if the added elements are the one's you're looking for.

Upvotes: 1

Related Questions