user10099944
user10099944

Reputation:

How to find class in the closest tag?

How can I find class in a closest tag using Java Script? Need to find 'customer' class in . The example as below:

       <tr>
            <td class="customer">
                @Html.DisplayFor(modelItem => item.Cust)
            </td>
            <td>
                <select id="decisionList">
                    <option value="0" selected></option>
                    <option value="1">None</option>
                </select>
            </td>
       </tr>

I tried this in JS:

document.querySelectorAll("#decisionList").forEach(elem => elem.addEventListener("change", function () {

    var selectedOptionIndex = this.options[this.selectedIndex].index;  //this works perfectly
    var invoiceDateText = this.closest('tr').find('customer').textContent; //this doesn't work

// ...some other code

Upvotes: 0

Views: 62

Answers (2)

Josh Bonnick
Josh Bonnick

Reputation: 2823

The closest method uses the querySelector to find the closest.

    var invoiceDateText = this.closest('.customer').textContent;

This should then search the DOM towards the document root for the closest element with the customer class.

If you wanted to search for the closest tr with a cell with customer class than you would modify that to.

    var invoiceDateText = this.closest('tr>.customer').textContent;

Upvotes: 0

QuestionMark
QuestionMark

Reputation: 26

I think this is what you're looking for:

document.querySelector("#decisionList").addEventListener('change', function() {
  const selectedOptionIndex = this.options[this.selectedIndex].index;
  const invoiceDateText = this.closest('tr').querySelector('.customer').textContent;
});

Upvotes: 0

Related Questions