Permalink
Switch branches/tags
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
13 lines (11 sloc) 2.61 KB
---
layout: post
title: Using getElementsBySelector in ScriptSharp
date: '2008-08-16T01:24:00.001+01:00'
tags:
modified_time: '2008-08-16T01:24:16.452+01:00'
blogger_id: tag:blogger.com,1999:blog-4015568221071268916.post-3662925185263493892
comments: true
blogger_orig_url: http://serialseb.blogspot.com/2008/08/using-getelementsbyselector-in.html
---
<p>I’m on my way to my second spike for one of my clients on playing with ScriptSharp to extend Rasta with Ajax functionality, and really wanted to be able to select elements as I would in CSS, using selectors (something I got quite used to with jQuery).</p> <p>ScriptSharp comes with various assemblies you can link to. The one called sscorlib is a .net mapping over a javascript library that extends document to have a getElementsBySelector method. But for some reason, ScriptSharp doesn’t map that method.</p> <p>So how do you call random code in ScriptSharp without resorting to evil eval code? You create a function of course! Here’s the snippet.</p> <div style="font-size: 10pt; background: #1a1a1a; color: #e0e0e0; font-family: consolas, courier new"> <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #00bfff">public</span> <span style="color: #00bfff">static</span> <span style="color: #00d2d2">DOMElement</span>[] GetElementsBySelector(<span style="color: #00bfff">string</span> selector, <span style="color: #00d2d2">DOMElement</span> root)</p> <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p> <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #00bfff">return</span> <span style="color: #00bfff">new</span> <span style="color: #00d2d2">Function</span>(<span style="color: #fa8072">&quot;return document.getElementsBySelector(selector, arg);&quot;</span>, <span style="color: #fa8072">&quot;selector&quot;</span>, <span style="color: #fa8072">&quot;arg&quot;</span>)</p> <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #a6a0e0">.</span>Call(<span style="color: #00d2d2">Document</span><span style="color: #a6a0e0">.</span>DocumentElement, selector, root) <span style="color: #00bfff">as</span> <span style="color: #00d2d2">DOMElement</span>[];</p> <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p> </div> <p></p> <p></p> <p></p> <p></p> <p></p> <p></p> <p>We define a function that calls the correct javascript code, declare the argument names we will pass it, and finally call it by passing our selector and the root.</p> <p>In one word, sweet.</p>