简体   繁体   中英

removeAttribute not applying for last element in an array

I have an array of elements that I use to search for the corresponding HTML using JQuery that I then need to remove attributes from. My function looks like this:

for (const block of collection) {
            //selectedBlock is returned as an array that I only want the first element of
            const selectedBlock = $('g').find(`[data-type='` + block.attributes.type + `']`)[0];
            selectedBlock.removeAttribute('pointer-events');
            selectedBlock.removeAttribute('opacity');
}

The code works for every element in the array except the last one. I've tried to debug it and it runs through the function just fine, but the removed attributes still remain afterwards. If I force an out of bounds error by running the loop collection.length+1 times, it works but then I get the out of bounds error. Why does the function not affect the last element despite the code being executed on it normally?

Edit:

I made a jsfiddle https://jsfiddle.net/1w04y6kr/4/ with all the basic components of what I'm trying to do (some <g>s with the attributes data-type/pointer-events/opacity, and some code to find the first of each data-type and remove the attributes). This example works 100%, but the same logic is in my project and it's still just not removing pointer-events/opacity from only the last element of collection

Update

@Wimanicesir was correct, the problem was somewhere else in the project (a seemingly unrelated area too, will have to investigate that) that was adding the attributes back to the last element after executing the above code. A simple reordering of functions fixed it.

Try a different approach. With HTML / SVG / XML like this:

<g data-type='type1' pointer-events='none' opacity='0.8'>Example 1</g>
<g data-type='type2' pointer-events='none' opacity='0.8'>Example 1</g>
<g data-type='type1' pointer-events='none' opacity='0.8'>Example 1</g>
const collection = ['type1', 'type2'];

collection.forEach(blockType =>
  $(`g[data-type="${blockType}"]`)
    .removeAttr('pointer-events')
    .removeAttr('opacity')
);

Usually in HTML, pointer-events and opacity would be CSS, not HTML properties. If so, use:

collection.forEach(blockType =>
  $(`g[data-type="${blockType}"]`).css({
    'pointer-events': 'initial',
    'opacity': 'initial',
  })
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM