最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to call a function in every element in the DOM even if they are dynamically created - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question edited Apr 11, 2016 at 13:23 fguillen asked Sep 5, 2013 at 18:56 fguillenfguillen 39k24 gold badges165 silver badges235 bronze badges 7
  • 1 Sorry, there's no easy or clean way of doing this cross-browser, assuming you're actually doing something other than .css. – Kevin B Commented Sep 5, 2013 at 18:57
  • 1 Was cross-browser mentioned in the question? – Robert Harvey Commented Sep 5, 2013 at 18:58
  • 6 Why don't you just add background-color: pink; to your CSS for the .red rule? – Ian Commented Sep 5, 2013 at 18:58
  • 2 jsfiddle/j08691/22kwt/1 – j08691 Commented Sep 5, 2013 at 18:59
  • 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. – Dark Falcon Commented Sep 5, 2013 at 19:05
 |  Show 2 more ments

2 Answers 2

Reset to default 7

You were close. Try:

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

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

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

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; }");

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论