Dorokhov.codes

jQuery Objects

Selectors

Function $ is used to search for elements. It returns a jQuery object.

Get an element by ID:

$("#some-element-id")

Get en element by tag:

$("some-element-tag")

Creating jQuery objects

Example:

var imgHtml = '<img src="http://example.com/images/example.png">';

var imgElement = $(imgHtml);

imgElement.css({
    position: "absolute",
    left: 10,
    top: 10
});

$("body").append(imgElement);

Manipulation with elements

We manipulate with DOM-elements using jQuery objects.

Function Description Example
text() Sets or gets text from an element. text(“Some text string”)
append() Adds new elements to DOM. append("<p>Some HTML</p>")
fadeOut() Animatedly hides an element. fadeOut(2000)
fadeIn() Animatedly shows an element. fadeIn(2000)
slideUp() Animatedly hides an element using slide effect. slideUp(2000)
slideDown() Animatedly shows an element using slide effect. slideDown(2000)
show() Make en element visible instantly. show()
hide() Make en element hidden instantly. hide()
delay() Delay animation on an element. delay(2000)
fadeTo() Add transparency to en element with animation. fadeTo(2000, 0.5)
offset() Sets offsets of an element (CSS: left, top… properties). offset({left: 100})
css() Sets CSS properties. css({position: “absolute”})

Chaining

Chaining is a technique that allows us to run multiple jQuery commands, one after the other, on the same element(s).

This way, browsers do not have to find the same element(s) more than once.

Example:

$("#p1").css("color", "red").slideUp(2000).slideDown(2000);