html - Jquery dynamically adding classes -


hi im working mask plugin , need add class input level element, can't seem target correctly, , .next() goes on next level <td>.

here jfiddle i'm working on can see need phone_us part added dynamically class attribute because im masking it<input type="text" class="" name="" value="">

javascript

$(document).ready(function(){  $('td').each(function (index) {    var divhtml =  $(this).text();    if(divhtml.indexof("phone") >= 0)      {     $(this).next().css('background-color', 'blue');            $(this).next().closest('input').addclass('phone_us');     $('.phone_us').mask('(999) 999-9999');      } }); }); 

html

<td class="label">phone #</td> <td class="field"><input type="text" class="label_box" name="" value=""></td> 

.closest() selects closest matching parent/grandparent... of selected element:

for each element in set, first element matches selector testing element , traversing through ancestors in dom tree.

use find or children method instead:

$('td:contains("phone")').next()                          .css('background-color', 'blue')                                 .find('input')                          .addclass('phone_us')                          .mask('(999) 999-9999'); 

http://jsfiddle.net/dynzg/


Comments