Find elements using part of ID

前端 未结 6 1554
予麋鹿
予麋鹿 2021-01-05 05:54

I have, the div\'s where id looks like this_div_id_NUMBER, all div\'s has the different NUMBER part. How I find all

6条回答
  •  一个人的身影
    2021-01-05 06:34

    you can use querySelectorAll to hit partial attribs, including ID:

    document.querySelectorAll("[id^='this_div_id']")
    

    the ^ next to the equal sign indicates "starts with", you can use * instead, but it's prone to false-positives.

    you also want to make sure to use quotes (or apos) around the comapare value in attrib selectors for maximum compatibility on querySelectorAll; in jQuery and evergreen browsers it doesn't matter, but in vanilla for old browsers it does matter.

    EDIT: late breaking requirement needs a more specific selector:

    document.querySelectorAll("[id^='this_div_id']:not([id$='_test_field'])");
    

    the not() segment prevents anything ending with "_test_field" from matching.


    proof of concept / demo: http://pagedemos.com/partialmatch/

提交回复
热议问题