简体   繁体   中英

How to select an element with an attribute that contains certain text?

I have this HTML code:

<li class="_33c randomtext3" data-gt="{&quot;alert_id&quot;:1576605904117859,&quot;notif_type&quot;:&quot;pub_comment&quot;,&quot;from_uids&quot;}">
<li class="_33c randomtext5" data-gt="{&quot;alert_id&quot;:1576605904117859,&quot;notif_type&quot;:&quot;year_comment&quot;,&quot;from_uids&quot;}">
<li class="_33c randomtext4" data-gt="{&quot;alert_id&quot;:1576605904117859,&quot;notif_type&quot;:&quot;group_comment&quot;,&quot;from_uids&quot;}">
<li class="_33c randomtext7" data-gt="{&quot;alert_id&quot;:1576605904117859,&quot;notif_type&quot;:&quot;pub_comment&quot;,&quot;from_uids&quot;}">
<li class="_33c randomtext5" data-gt="{&quot;alert_id&quot;:1576605904117859,&quot;notif_type&quot;:&quot;pub_comment&quot;,&quot;from_uids&quot;}">

The order of the lines is varied, (using [2] doesn't work)

I want to delete the <li> with a certain text ( data-gt="...group_comment..." ), "group_comment" is the certain text (the line 3, sometimes it is on another line).

I tried with document.querySelectorAll('[data-gt]'); with a NodeList(5) , but how to find in that NodeList the certain text?

Thank you.

Use the attribute value selector and wildcard selector.

document.querySelectorAll('li[data-gt*=group_comment]')

See https://www.geeksforgeeks.org/wildcard-selectors-and-in-css-for-classes/

 const matches = document.querySelectorAll('[data-gt*="group_comment"]') matches.forEach( x => x.classList.add("hidden") )
 .hidden { display: none; }
 <ul> <li class="_33c randomtext3" data-gt="{&quot;alert_id&quot;:1576605904117859,&quot;notif_type&quot;:&quot;pub_comment&quot;,&quot;from_uids&quot;}"> pub_comment </li> <li class="_33c randomtext5" data-gt="{&quot;alert_id&quot;:1576605904117859,&quot;notif_type&quot;:&quot;year_comment&quot;,&quot;from_uids&quot;}"> year_comment </li> <li class="_33c randomtext4" data-gt="{&quot;alert_id&quot;:1576605904117859,&quot;notif_type&quot;:&quot;group_comment&quot;,&quot;from_uids&quot;}"> group_comment </li> <li class="_33c randomtext7" data-gt="{&quot;alert_id&quot;:1576605904117859,&quot;notif_type&quot;:&quot;pub_comment&quot;,&quot;from_uids&quot;}">pub_comment</li> <li class="_33c randomtext5" data-gt="{&quot;alert_id&quot;:1576605904117859,&quot;notif_type&quot;:&quot;pub_comment&quot;,&quot;from_uids&quot;}">pub_comment</li> </ul>

You should use attribute selector combined with the contains modifier *

const commments = document.querySelectorAll('[data-gt*="group_comment"]')

You can see the different modifiers here: Attribute Selectors

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