简体   繁体   中英

Find a data-attribute within a class that is equal to a variable

Please no jquery Im trying to delete an element inside list with the same data-id as foo

let foo = document.querySelector('.foo');
let list = document.querySelector('.listing-filter');
let fooId = foo.dataset.id;
let listId = list.dataset.id;

let listingFilter = () => {
    if ( typeof fooId !== 'undefined' && typeof listId !== 'undefined'){
        //This is what I cant seem to figure out
        let deleteMe = document.querySelector('.listing-filter[data-id = fooId]')

        //This should only be the data-id in list that changes not in el1
        deleteMe.setAttribute('data-id', 'hidden')
     }
}

Then in css i can select it [data-id="hidden"] and hide the element.

I cant seem to figure out how to select in list the list element that has the same data-id as foo, and then manipulate it.

document.querySelector('.listing-filter[data-id="fooId"]')

您可以尝试更新查询选择器字符串吗?

You're almost there:

let deleteMe = document.querySelector('.listing-filter [data-id="' + fooId + '"]');

Moreover you don't need .foo

let list = document.querySelector('.listing-filter');
let listId = list.dataset.id;

let listingFilter = () => {
    if (typeof listId !== 'undefined'){
      let deleteMe = document.querySelector('.listing-filter [data-id="' + listId + '"]');
      deleteMe.setAttribute('data-id', 'hidden')
    }
}

You've typed in fooId directly, so it'll look for something with data-id="fooId" rather than your defined fooId value. Try adding your variable to the string:

let deleteMe = document.querySelector(`.listing-filter[data-id=${fooId}]`)

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