Steven's Blog

A Dream Land of Peace!

Jquery 拾遗

This blog post is about some of the usages of jQuery while I am learning and using jQuery. I keep a note of it so that I can pick it up conveniently later.

  1. append a paragraph to the front of your body.
1
2
var para = $("<p>", {"text": "I'm a new paragraph!", "css":{"background":"yellow"}});
$("body").prepend(para)

and also we can do it using the “prepentTo” method.

1
$("<p>", {"text": "I'm a new people!", "css":{"background":"red"}}).prependTo("body");

If we want to insert before/after an element, we can use the following method.

1
$("<p>", {"text": "a new paragraph."}).insertAfter("p.foo");

For the “wrap” method, it is like this:

1
$("span").wrap("<strong />");

This will wrap all “span”” tag with “strong” tag. Or we can have the nested tags inside “wrap”:

1
$("span").wrap("<strong><em></em></strong>");
  1. We can also use callback function to do some selective adding.
1
$("span").wrap(function(){return $(this).is(".foo") ? "<strong>" : "<em>"});
  1. to get the last id attributes of a paragraph:
1
$("p:eq(3)").attr("id");

and to modify its id to “bar”, we can do this:

1
$("#bar").attr("id", "bat")
  1. if you want to remove an attribute from an element, we can use the “removeAttr” method.
1
$(":checkbox").removeAttr("disabled");
  1. text() can just act on “text”, while html() can act on html contents.

  2. .val() is used to get the value or content of a form element, like:

1
$(":submit").val();

or

1
$(":submit").val("Sign IN");
  1. .addClass(), .removeClass(), .toggleClass() are also 3 often used methods.

  2. .map() and .each(), .show() and .hide(), .fadeIn(), .fadeOut(), .fadeTo() , these are common methods.