5

How would i apply css style s to the dynamically created table element?? tblResult is a dynamic table i am creating .

<script type="text/javascript">
  $(document).ready(function () {
    $('#tblResult tbody tr').on('mouseover', function () {
     $(this).addClass('highlightRow');

  });

 });

Is It true that .addClass will not work with the dynamic controls in jquery?

Suppose If i want to add class to child element:

  $('body').on('mouseover', '#tblResult tbody tr td #im', function () {
    $(this).addClass('transition');
  });

Is that ok??

2 Answers 2

4

Since your table have been added dynamically to the DOM, all the events will not be available to this table and elements such as <tr> or <td> inside it. In this case, you need to use event delegation:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.

$(document).ready(function () {
    $('body').on('mouseover','#tblResult tbody tr',function() {
        $(this).addClass('highlightRow');
    });
});

So basically, event delegation will help you to attach mouseover event to these newly created <tr> elements in this case.

Sign up to request clarification or add additional context in comments.

5 Comments

But why it is not applying??
The time the event binding code executes the tr is not present and using event delegation will bind the event when tr is added
Thanx for the info on Dynamic controls!! U v helpd me out!!
suppose if i want to add a class to particular element in table? see in edit please
You can use: $('#im').addClass('transition');
2

Why don't you apply the css for the tr directly in css instead of adding an event?

tr:hover{
  background-color: #BADA55;
}

check out the fiddle

2 Comments

Ya!! Even i can do that!! But i want to use dynamic events binding using 'on'
if you to use dynamic events, you have to do what @Felix said, you didn't share your full html and js, so i assume tblResult itself is dynamically added. In your code snippet, during document.ready, you are trying to hook up the event handler to an non-existent DOM object, that's why @Felix's answer gave jquery a 'context', which was 'body', for jquery to observe this particular element

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.