Nerius Jok
Nerius Jok

Reputation: 3237

select element where its attribute like sibling component attribute [selectors]

Is that posible and also is here a way to select element according to sibbling attribute value?

AS i have element by which i want to get id value:

<tr amount=1 prid="product_1-2">

And compare to siblings which seems like:

<tr amount=2 id="item_23_product_1-2">

I wish toggle empty tr elements and its siblings according to attribute similarity. What is a right way to select both, now i have this:

tr[amount=''], tr[amount=''] ~ tr[id$=sibling_attribute_id]

I cannot wrap inside tbody(already used for same reason).

Toggle function:

const toggleEmpty = ({target}) => {
  const selector = 'tr[amount=""], tr[amount=""] ~ tr[id$=child id]'
  if (target.getAttribute('name') == 'show_empty')
    $(selector).show();
  else
    $(selector).hide();  
}

Upvotes: 0

Views: 149

Answers (1)

Boy
Boy

Reputation: 1199

Here is how it could be done using XPath, but you will have to add your "show_empty" logic, if you need help, ask.

const hide  = function (target) {
    let prid = target.getAttribute("prid");
    let nodesSnapshot = document.evaluate("./*[substring(@id,string-length(@id) -string-length('" + prid + "') +1) = '" + prid + "']",
        target.parentNode, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

    for ( let i=0 ; i < nodesSnapshot.snapshotLength; i++ ){
        // let itemElement = nodesSnapshot.snapshotItem(i);
        // console.dir(itemElement);
        nodesSnapshot.snapshotItem(i).style.display = "none";
    }
};
<table>
    <tbody>
        <tr prid="product_1-2" onclick="hide(this)">
            <td>prid product_1-2</td>
        </tr>
        <tr id="item_1_product_1-2">
            <td>item_1_product_1-2</td>
        </tr>
        <tr id="item_2_product_1-2">
            <td>item_2_product_1-2</td>
        </tr>
        <tr id="item_3_product_1-3">
            <td>item_3_product_1-3</td>
        </tr>
        <tr id="item_4_product_1-3">
            <td>item_4_product_1-3</td>
        </tr>
    </tbody>
</table>

Upvotes: 1

Related Questions