getElement, getStyle, addEvents

Selecting descendants. Adding multiple events to multiple elements. Getting multiple styles.

by andfinally

HTML

<div id="container" class="clearfix">
    <div id="content1" class="content">
        One for all and all for one, Muskehounds are always ready. One for all and all for one, helping everybody. One for all and all for one, it's a pretty story. Sharing everything with fun, that's the way to be. One for all and all for one, Muskehounds are always ready.
    </div>
    <div id="content2" class="content">
        Ten years ago a crack commando unit was sent to prison by a military court for a crime they didn't commit. These men promptly escaped from a maximum security stockade to the Los Angeles underground. 
    </div>
    
</div>

<ul id="list" class="clearfix">
    <li id="li1" class="first">Bacon and eggs</li>
    <li id="li2">Eggs Benedict</li>
    <li id="li3">Oatmeal porridge with banana</li>
    <li id="li4">Waffles with maple syrup</li>
    <li id="li5">Muesli</li>
</ul>

<div id="output"></div>

CSS

.content
{
    float: left;
    width: 250px;
    margin: 10px;
    padding: 10px;
    border: 1px solid #999;
    background: #eee; 
}

.clearfix:after
{
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

li
{
    float: left;
    width: 100px;
    margin: 10px;
    padding: 10px;
    border: 1px solid #ccc;
    background: #dedede;  
    cursor: pointer;
}

.injected
{
    clear: both;
    border: 1px solid #ccc; 
    margin: 10px;
    padding: 10px;
}

#output
{
    width: 320px;
    min-height: 50px;
    margin: 10px;
    padding: 10px;
    border: 1px dashed #ccc;   
}

JavaScript

///// GETELEMENT /////

// Pass tag name or CSS selector - returns first match in container
$('container').getElement('div').setStyle('background', '#FAE6EB');

// Pass tag name or CSS selector. Returns all descendant matches
$('list').getElements('li').setStyle('background', '#DFEBF5');

// Select alternate elements only
$('list').getElements('li:even').setStyle('color', 'red');

// Adding events to all selected elements
$('list').getElements('li').addEvents({
    mouseenter: function() {
        event.target.setStyle('borderWidth', 10);
    },
    mouseleave: function() {
        event.target.setStyle('borderWidth', 1);
    }
});


//// GETSTYLE /////

var output = 'The bg colour of content1 is ' + $('content1').getStyle('background') + '<br>';
var styles = $('content2').getStyles('background', 'margin');
output += 'The margin of content2 is ' + styles.margin;
$('output').set('html', output);