0

Hi im working with a mask plugin and I need to add a class to an input level element, however I can't seem to target it correctly, and .next() simply goes on to the next level <td>.

Here is a Jfiddle I'm working on as you can see I need the phone_us part to be added dynamically to the 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>

1 Answer 1

3

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

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the 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/

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

2 Comments

I see. Is next() any different then each() is this context?
@Undermine2k No, there is no difference, it selects the very next sibling of the selected elements.

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.