I have some JSON that contains thousands of different CSS selectors, here's a sample of the variety...
"#mid_ad_title",
"#mid_mpu",
"#mid_roll_ad_holder",
".SidebarAdvert",
".SitesGoogleAdsModule",
".SkyAdContainer",
"a[href$=\"/vghd.shtml\"]",
"a[href*=\"/adrotate/adrotate-out.php?\"]",
"a[href^=\"http://ad-apac.doubleclick.net/\"]",
"#mn #center_col > div > h2.spon:first-child + ol:last-child",
"#resultspanel > #topads",
"#rhs_block > #mbEnd"
So as you can see, the JSON is made up of a variety of selectors - some are just a class, some are just an ID and some are a mixture.
I'd like to use the relevant JavaScript "get" method depending on the type of selector, so for selectors that are just IDs I'd use document.getElementById()
, etc.
Does anyone know of any regular expressions or something that will tell me the type of selector when I loop through the JSON? Ie "class", "id", "other"
.
Thanks in advance.
I think you'll find more use in a switch
:
var results = [];
for(var i = 0; i < selectors.length; i++){
var s = selectors[i];
if( s.indexOf(' ') !== -1){
s = s.substring(0, s.indexOf(' '));
}
switch(selectors[i][0]){
case '#': // ID
results.push(document.getElementById(s.substr(1)));
break;
case '.': // Class
results.push(document.getElementsByClassName(s.substr(1)));
break;
default: // Tag
results.push(document.getElementsByTagName(s));
break;
}
}
However , the only reliable solution would be to use:
document.querySelectorAll(selector);
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.