<?xml version="1.0" encoding="utf-8"?>
<feed xml:lang="en-us" xmlns="http://www.w3.org/2005/Atom"><title>Simon Willison's Weblog: getelementsbyselector</title><link href="http://simonwillison.net/" rel="alternate"/><link href="http://simonwillison.net/tags/getelementsbyselector.atom" rel="self"/><id>http://simonwillison.net/</id><updated>2003-03-25T23:38:24+00:00</updated><author><name>Simon Willison</name></author><entry><title>getElementsBySelector()</title><link href="https://simonwillison.net/2003/Mar/25/getElementsBySelector/#atom-tag" rel="alternate"/><published>2003-03-25T23:38:24+00:00</published><updated>2003-03-25T23:38:24+00:00</updated><id>https://simonwillison.net/2003/Mar/25/getElementsBySelector/#atom-tag</id><summary type="html">
    &lt;p&gt;Inspired by &lt;a href="http://blog.mooncalf.me.uk/archive/2003/03/25#RefinedClassFetching" title="document.getElementsByClassName"&gt;Andy&lt;/a&gt;, I decided to have a crack at something I've been thinking about trying for a long time. &lt;a href="/static/2003/getElementsBySelector.js" title="getElementsBySelector.js"&gt;&lt;code&gt;document.getElementsBySelector&lt;/code&gt;&lt;/a&gt; is a javascript function which takes a standard &lt;acronym title="Cascading Style Sheets"&gt;CSS&lt;/acronym&gt; style selector and returns an array of elements objects from the document that match that selector. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;document.getElementsBySelector('div#main p a.external')
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will return an array containing all of the links that have 'external' in their &lt;code&gt;class&lt;/code&gt; attribute and are contained inside a paragraph which is itself contained inside a div with its &lt;code&gt;id&lt;/code&gt; attribute set to 'main'.&lt;/p&gt;

&lt;p&gt;So far I've only tested it on Phoenix but it seems to work as intended for the small number of test cases I've tried. If you spot any bugs please let me know. I'm about to fire up a Windows &lt;acronym title="Personal Computer"&gt;PC&lt;/acronym&gt; and see how much it breaks in &lt;acronym title="Internet Explorer"&gt;IE&lt;/acronym&gt;...&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Update:&lt;/strong&gt; I've put together a &lt;a href="/static/2003/getElementsBySelector.html" title="document.getElementsBySelector Demo"&gt;demo page&lt;/a&gt; showing the function in action. It works fine in &lt;acronym title="Internet Explorer"&gt;IE&lt;/acronym&gt; 6.&lt;/p&gt;
    
        &lt;p&gt;Tags: &lt;a href="https://simonwillison.net/tags/css"&gt;css&lt;/a&gt;, &lt;a href="https://simonwillison.net/tags/getelementsbyselector"&gt;getelementsbyselector&lt;/a&gt;, &lt;a href="https://simonwillison.net/tags/javascript"&gt;javascript&lt;/a&gt;, &lt;a href="https://simonwillison.net/tags/projects"&gt;projects&lt;/a&gt;&lt;/p&gt;
    

</summary><category term="css"/><category term="getelementsbyselector"/><category term="javascript"/><category term="projects"/></entry></feed>