Skip to content

API CSS Selectors and Traversal methods

ajithhub edited this page Jan 24, 2011 · 5 revisions

getHtml and postHtml return a special object $ that wraps node-soupselect and aids in selecting and traversing DOM elements.

$(selector) returns an element or collection of elements.

Some example selectors (see node-soupselect for more)

 $('a')                         //Select all A tags
 $('a.foo')                     //Select all A tags of the class 'foo'
 $('a.foo.bar')                 //Select all A tags of the class 'foo' and the class 'bar'
 $('#container')                //Select the element with id = 'container'
 $('p a')                       //Select all A tags that have a parent P tag
 $('input[type=text]')          //Select all text inputs

Working with a collection of elements

$('a').first()                  //Returns the first A tag
$('a').last()                   //Returns the last A tag
$('a').each(callback)           //Calls `callback` with each A tag
$('a').each(attrib, callback)   //Calls `callback` with an attribute of each A tag, e.g. $('a').each('href', function(href){});
$('a').has(selector)            //Removes elements that do not have a descendent that matches the selector
$('a').odd(callback)            //Calls `callback` with the 1st, 3rd, 5th, ... element
$('a').even(callback)           //Calls `callback` with the 2nd, 4th, 6th, ... element

Working with an element

<a href="hello.htm">Hello <b>World!</b></a>

$('a').text                     //Outputs the text DIRECTLY inside the tag
    // => outputs 'Hello'
    
$('a').fulltext                 //Outputs the text inside the tag including the text inside of each nested tag
    // => outputs 'Hello World!'

$('a').innerHTML                
    // => outputs 'Hello <b>World!</b>'
    
$('a').attribs.href
    // => outputs 'hello.htm'

Note: text and fulltext trim the result, replace <br> and <br /> with \n, and automatically decode HTML entities. If you wish to access the raw text, use the following getters:

$('a').rawtext;        //Raw version of text
$('a').striptags;      //Raw version of fulltext

You can also specify a custom context when using $ by calling $(selector, context)

Clone this wiki locally