JoJo
JoJo

Reputation: 4933

Change a child class element's HTML using jQuery based off parent ID?

I am trying to change the HTML of a div element, to simple renumber the rows. I cannot seem to grab the child element that has a class="Col1" value. How can it be done correctly using jQuery?

function reorderTimeRowDisplayNumbers() {
    var elementsDisplayVisible = $(".schedTable").filter(':visible');
    if (elementsDisplayVisible.length > 0) {

        for (i = 1; i <= elementsDisplayVisible.length; i++) {

            var elementDisplayVisibleID = elementsDisplayVisible[i - 1].id;
            var myInt = parseInt(elementDisplayVisibleID.match(/[0-9]+/)[0], 10);

            alert(myInt);

            // update child div innerHTML
            if (myInt != i) {
                var divEl = document.getElementById(elementDisplayVisibleID);
                alert(divEl);
                $('#' + divEl + ' > .Col1').html(i -1);                
            }
        }
    }
}

Final jQuery solution:

function reorderTimeRowDisplayNumbers() {
    // Renumber Display Number only. Called when adding or removing rows.
    $('.schedTable:visible').each(function (index) {
        if (Number(this.id.match(/[0-9]+/)[0]) !== (index)) {
            $(this).children('.col1').html(index + 1);
        }
    });

Upvotes: 0

Views: 1654

Answers (2)

Felix Kling
Felix Kling

Reputation: 816900

You are trying to convert a DOM element to a string and use it in a selector. That won't work. You can use one of the many traversal methods jQuery offers:

$(divEl).children('.Col1')

And here is a more succinct version of your code:

function reorderTimeRowDisplayNumbers() {
    $('.schedTable:visible').each(function(index) {
        if (Number(this.id.match(/[0-9]+/)[0]) !== (index + 1)) {
            $(this).children('.Col1').html(index);
        }
    });
}

Upvotes: 3

PeterKA
PeterKA

Reputation: 24638

You already have the ID you need plugin in there. You actually meant to write:

$('#' + elementDisplayVisibleID + ' > .Col1')

Upvotes: 3

Related Questions