How to call a function in every element in the DOM even if they are dynamically created
Asked Answered
P

2

2

I want to call a function over specific elements on my DOM, for example:

$(".red").css({backgroundColor: "pink"});

It works ok for any element already existing into the DOM, but I also want to this method to be called in elements dynamically added to the DOM.

I've tried things like:

$(".red").on(function(){ this.css({backgroundColor: "pink"}) });

or:

$(".red").on("load", function(){ this.css({backgroundColor: "pink"}) });

But not any success.

Check the jsFiddle

Update

The .css() call is just an example I actually want to call other kind of functions

Prenomen answered 5/9, 2013 at 18:56 Comment(7)
Sorry, there's no easy or clean way of doing this cross-browser, assuming you're actually doing something other than .css.Diadiabase
Was cross-browser mentioned in the question?Elwoodelwyn
Why don't you just add background-color: pink; to your CSS for the .red rule?Loupe
jsfiddle.net/j08691/22kwt/1Alexisaley
No, there is not a generic way to call any function on all DOM elements, even those dynamically added. There are ways in code to set styles that apply to all elements. Please explain what you are trying to do.Ziegfeld
After your update, this problem becomes really more complex.Intercalate
@lan @Alexisaley Sorry for the misunderstanding.. the .css() call is just an examplePrenomen
T
7

You were close. Try:

$(document).on("load", ".red", function(){ this.css({backgroundColor: "pink"}) });

Oops, that doesn't work. This does http://jsfiddle.net/4Bv9r/

$('body').on('DOMNodeInserted', ".red", function(){ $(this).css({backgroundColor: "pink"}) });
Truesdale answered 5/9, 2013 at 19:1 Comment(4)
this doesn't work. jsfiddle.net/22kwt/2 paragraph tags don't have a load event.Diadiabase
Just a note, DOMNodeInserted doesn't work on IE8 and below.Alexisaley
If you need to do IE, look at onreadystatechange and/or propertychange events. #2144429 & https://mcmap.net/q/1634417/-domnodeinserted-in-the-ieTruesdale
@Prenomen And if you want to support newer browsers since DOMNodeInserted is deprecated, you can use a MutationObserver: developer.mozilla.org/en-US/docs/Web/API/MutationObserver . You can detect support and fallback to older methodsLoupe
S
1

If you know the element is going to be added dynamically, the best way should be adding the rules to a stylesheet.

OR you can create style dynamically,

$("<style>").text(".red { background-color: pink; }").appendTo("head");

OR

Add this in your page <style id='d_style'></style> then

$('#d_style').text(".red { background-color: pink; }");
Sanfordsanfourd answered 5/9, 2013 at 19:5 Comment(3)
I think it'll be troublesome on IEIntercalate
If what you're trying to do is as simple as changing the css, this is a much better solution.Truesdale
Sorry for the misunderstanding.. the .css() call is just an examplePrenomen

© 2022 - 2024 — McMap. All rights reserved.