This chapter covers
- Manipulating element class names
- Setting the content of DOM elements
- Getting and setting form element values
- Cloning DOM elements
- Modifying the DOM tree by adding, moving, or replacing elements
5.1 Changing element styling
5.1.1 Adding and removing class names
addClass(names)
Parameters
names (String|Function)
Returns
The jQuery collection.
var elements = document.getElementsByClassName('some-class');
for(var i = 0; i < elements.length; i++) {
elements[i].classList.add('hidden');
}
$('.some-class').addClass('hidden');
removeClass(names)
Parameters
names (String|Function)
Returns
The jQuery collection.
$('#text').removeClass('hidden');
toggleClass([names] [,switch])
Parameters
names (String|Function)
switch (Boolean)
Returns
The jQuery collection.
$('.share-widget').click(function () {
$('.socials', this).toggleClass('hidden');
});
if (aValue === 10) {
$('p').addClass('hidden');
} else {
$('p').removeClass('hidden');
}
$('p').toggleClass('hidden', aValue === 10);
$('p').toggleClass(function (index) {
return (index % 2 ===0) ? 'hidden' : ' ' ;
});
hasClass(name)
Parameters
names (String)
Returns
true or false.
$('p:first').hasClass('surprise-me');
5.1.2 Getting and setting styles
css(name, value)
css(properties)
Parameters
name (String)
value (String|Number|Function)
properties (Object)
Returns
The jQuery collection.
$('.expandable').css('width', function (index, currentWidth) {
return parseInt (currentWidth, 10) + 20 *index;
});
$('.expandable').css('width', '+=20');
$('p').css({
margin: '1em',
color: '#fff',
opacity: 0.8
});
$('p').css({
margin: '1em',
color: '#fff',
opacity: function (index, currentValue) {
return 1- ((index % 10) / 10);
}
});
css(name)
Parameters
name (String|Array)
Returns
The computed value as a string or an object of property-value pairs.
var styles = $('.special').css([
'font-size', 'color', 'text-decoration'
]);
for (var property in styles) {
console.log(property + ': ' + styles[property]);
}
width(value)
height(value)
Parameters
value (Number|String|Function)
Returns
The jQuery collection.
$('div').width(500);
$('div').css('width', 500);
width()
height()
Parameters
none
Returns
The computed width or height as a number in pixels;null
if the jQuery object is empty.
function displayDimensions() {
$('#display').html(
$('#test-subject').width() + 'x' +$('#test-subject').height()
);
}
Additional jQuery dimension-related methods
Method | Description |
---|---|
innerHeight | |
innerHeight(value) | |
innerWidth() | |
innerWidth(value) | |
outerHeight | |
outerHeight(value) | |
outerWidth | |
outerWidth(value) |
offset()
Parameters
none
Returns
An object with left
and top
properties as numbers depicting the position in pixels relative to the document.
offset(coordinates)
Parameters
coordinates (Object|Function)
Returns
The jQuery collection.
position()
Parameters
none
Returns
An object with left
and top
properties as numbers depicting the positon in pixels relative to the closet offset parent.
Both offset()
and position
can only be used for visible elements.
The jQuery scroll bar control methods
Method | Description |
---|---|
scrollLeft() | |
scrollLeft(value) | |
scrollTop() | |
scrollTop(value) |
setTimeout (function () {
$('#elem').offset({
left: 0,
top: 0
});
}, 1000);
5.2 Setting element content
5.2.1 Replacing HTML or text content
html()
Parameters
none
Returns
The HTML content of the first matched element.
html(content)
Parameters
content (String|Function)
Returns
The jQuery collection.
$('#message').html('Your current balance is 1000$
');
text()
Parameters
none
Returns
A string of all the text contents.
text(content)
Parameters
content (String|Number|Boolean|Function)
Returns
The jQuery collection
5.2.2 Moving elements
append(content [, content, ..., content])
Parameters
content (String|Element|jQuery|Array|Function)
Returns
The jQuery collection
$('p').append('some text');
$('p.append-to').append($('a.append'));
$('#message').append(
'This
',
[
'is
',
$('').text('my')
],
$('
text
')
);
prepend(content [, content, ..., content])
Parameters
content Same as the content
parameter of append
Returns
The jQuery collection.
before(content [, content, ..., content])
Parameters
content Same as the content
parameter of append()
Returns
The jQuery collection.
after(content [, content, ..., content])
Parameters
content Same as the content
parameter of append()
Returns
The jQuery collection.
Method | Description |
---|---|
appendTo(target) | |
prependTo(target) | |
insertBefore(target) | |
insertAfter(target) |
5.2.3 Wrapping and unwrapping elements
wrap(wrapper)
Parameters
wrapper (String|Element|jQuery|Function)
Returns
The jQuery collection.
$('a.surprise').wrap('');
$('a.surprise').wrap($('div:first'));
wrapAll(wrapper)
Parameters
wrapper Same as the wrapper
parameter of wrap()
Returns
The jQuery collection.
wrapInner(wrapper)
Parameters
wrapper Same as the wrapper
parameter of wrap()
Returns
The jQuery collection.
unwrap()
Parameters
none
Returns
The jQuery collection.
5.2.4 Removing elements
remove([selector])
Parameters
selector (String)
Returns
The jQuery collection.
The elements that were removed from the DOM are still referenced by this set and can be further operated upon using other jQuery methods including appendTo()
, prependTo()
, insertBefore()
, insertAfter()
. But any data stored or event listener added to the removed element is lost.
detach([selector])
Parameters
selector (String)
Returns
The jQuery collection.
empty()
Parameters
none
Returns
The jQuery collection
var newContent = 'Wow, this new content is awesome!
'
$('#content')
.empty()
.html(newContent);
5.2.5 Cloning elements
clone([copyHandlesAndData[, copyChildrenHandlersAndData]])
Parameters
copyHandlersAndData (Boolean)
copyChildrenHandlersAndData (Boolean)
Returns
The newly created jQuery collection.
$('img').clone().appendTo('fieldset.photo');
$('ul').clone(true).insertBefore('#here');
$('a').clone(true, false).appendTo('div:first');
5.2.6 Replacing elements
replaceWith(content)
Parameters
content (String|Element|Array|jQuery|Function)
Returns
A jQuery collection containing the replaced elements.
$('img[alt]').each(function () {
$(this).replaceWith('' + $(this).attr('alt') + '');
});
replaceAll(target)
Parameters
target (String|Element|Array|jQuery)
Returns
A jQuery collection containing the inserted elements.
$('img[alt]').each(function () {
$('' + $(this).attr('alt') + '').replaceAll(this);
});
5.3 Dealing with form element values
val()
Parameters
none
Returns
The fetched value or values.
$('input[type="radio"][name="radio-group"]:checked').val();
var checkboxValues = $('input[type="checkbox"][name="checkboxgroup"]:checked').map(function () {
return $(this).val();
})
.toArray();
val(value)
Parameters
value (String|Number|Array|Function)
Returns
The jQuery collection.
$('input[type="checkbox"], select').val(['one', 'two', 'three']);
5.4 Summary
copy, move, replace, remove, append, prepend, wrap, manage the values of form elements