1

I am trying to get the table rowIndex from a td element in jQuery. This is what I'm trying:

var element = $('td').filter(function() { 
    var Text = $(this).contents()[0].textContent.trim();
    return parseInt(Text, 10) == some_Textvar;
});
var parent = element.parentNode;
var index = parent.rowIndex;

I'm getting the following error

Uncaught TypeError: Cannot read property 'rowIndex' of undefined(…)

html:

<div class="class1">
    <table class="class2">
        <tbody>
            <tr>
                <td>
                </td>
            </tr>
            <tr>
            ......

The element definitely exists because I work with it in the rest of my code. How can I get this row which this td element is in?

Thanks

2
  • Post your html. Commented Mar 2, 2017 at 11:38
  • @Kinduser edit made with html :) Commented Mar 2, 2017 at 11:40

1 Answer 1

2

element is jQuery object which doesn't have parentNode property thus it be undefined so error is expected.

Use .get()/[0] to get the reference of underlying DOM element, then you can access the property.

Retrieve the DOM elements matched by the jQuery object.

var parent = element.get(0).parentNode;
var index = parent.rowIndex;

As an alternate, Using jQuery you can use .index()

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements

var index = element.parent().index();
Sign up to request clarification or add additional context in comments.

2 Comments

I see, when I log the index to the console, I was expecting a number: 0,1,2 etc. Instead it returned a function ( elem ) { // No argument, return index in parent..... I'm very confused as to what this is...
@RuthYoung, Did you tried element.parent().index()?

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.