开发者

find a div without knowing full id

开发者 https://www.devze.com 2023-02-12 15:46 出处:网络
I\'m working on a chrome extension associated with a website. I want to change the text in a div but the div has a dynamic id and has no other ways for me to identify it (i.e. no class)

I'm working on a chrome extension associated with a website. I want to change the text in a div but the div has a dynamic id and has no other ways for me to identify it (i.e. no class)

the div looks like this开发者_如何学编程

<div id="button select-leg routing_idens-640bbf2f16,"> text... </div>

the div always has "button select-leg routing_idens-" in the id

could I use something similar to .find() that will find divs with the string that always occurs?


If you make your ID valid:

<div id="button_select-leg_routing_idens-640bbf2f16,"> text... </div>

You can use the the attribute-starts-with-selector(docs) :

$('div[id^="button_select-leg_routing_idens-"]')


In jQuery:

$('div[id^="button select-leg routing_idens-"]')


I think you will have to get by tag name (div) or use querySelectorAll('div') and then cycle through those returned elements checking their ID against a substring.

Heres an example. You will also have to correct your ID, with spaces it is invalid.

var elements = document.querySelectorAll('div');
for(var e in elements) {
    if(elements[e].id.indexOf('some_substring') !== -1) {
        // Now elements[e] contains the element you want.
    }
}


All of the modern JavaScript libraries (JQuery, Mootools, Dojo etc.) provide very efficient ways (selectors) to find certain elements on a page. You can iterate through the elements and select the 7th (if that is constant) or check if it's id starts with "button select-leg routing_idens-".

Jquery: jquery.com

Mootools: mootools.net

0

精彩评论

暂无评论...
验证码 换一张
取 消