get the nth-child number of an element in jquery

You can use jQuery’s index function for that. It tells you where the given element is relative to its siblings:

var index = $(this).index();

Live example | source

The indexes are 0-based, so if you’re looking for a 1-based index (e.g., where the first one is 1 rather than 0), just add one to it:

var index = $(this).index() + 1;

If you’re not using jQuery and came across this question and answer (the OP was using jQuery), this is also quite simple to do without it. nth-child only considers elements, so:

function findChildIndex(node) {
    var index = 1;                         // nth-child starts with 1 = first child
    // (You could argue that you should throw an exception here if the
    // `node` passed in is not an element [e.g., is a text node etc.]
    // or null.)
    while (node.previousSibling) {
        node = node.previousSibling;
        if (node && node.nodeType === 1) { // 1 = element
            ++index;
        }
    }
    return index;
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)