arrow_back
Back

jQuery objects: selectors, chaining, and the jQuery collection

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

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);
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

jQuery snippets: modals, forms, and common DOM patterns

arrow_forward