possible to parse a html page for div id's ...

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
krraleigh
Forum Commoner
Posts: 86
Joined: Tue Jul 17, 2007 2:52 pm

possible to parse a html page for div id's ...

Post by krraleigh »

Is it possible to parse a web page and capture the values of all the div id elements and store them into
an array obj if the match a reg expression of say /^F/d+$/ so that I can act on them depending on what they are?

Thanx
Kevin
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: possible to parse a html page for div id's ...

Post by kaszu »

One way is to take document.body.innerHTML and find all id=... , another way is to traverse all elements and check if they have ID's (or document.querySelectorAll('*[id]') if it's supported) and match against regular expression.
Here is second way:

Code: Select all

var els = [];
var ids = [];
 
//Get list of all elements (if possible only those which have IDs)
if (typeof document.querySelectorAll == 'undefined') {
    var els = document.getElementsByTagName('*');
} else {
    var els = document.querySelectorAll('*[id]');
}
 
for(var i=0,j=els.length; i<j; i++) {
    //Check if element has an ID and if it does, then match against your pattern
    if (els[i].id && els[i].id.match(/^F\d+$/)) {
        ids.push(els[i].id);
    }
}
 
alert(ids.length);
It was a lot faster in FF, which supports querySelectorAll, don't know how well it will do in IE.
Post Reply