jQuery in Action

Changing element styling
67
Now that we've explored manipulating the styles on a wrapped set of elements,
let's take a look at a couple of related style-oriented activities that you might want
to accomplish, and how to achieve them.
3.2.3 More useful style-related commands
It's extremely common to need to determine whether an element has a particular
class. With jQuery, we can do that by calling the
hasClass()
function.
$("p:first").hasClass("surpriseMe")
This will return
true
if any element in the matched set has the specified class. The
syntax of this command is as follows:
Recalling the
is()
command from chapter 2, we could achieve the same thing with
$("p:first").is(".surpriseMe")
In fact, jQuery's inner workings implement the
hasClass()
function exactly that
way! But arguably, the
hasClass()
command makes for more readable code.
Another commonly desired ability is to obtain the list of classes defined for a
particular element as an array instead of the cumbersome space-separated list.
We could try to achieve that by writing
$("p:first").attr("class").split(" ");
Recall that the
attr()
command will return
undefined
if the attribute in question
doesn't exist, so this statement will throw an error if the
<p>
element doesn't pos-
sess any class names. We could solve this by first checking for the attribute, and if
we wanted to wrap the entire thing in a repeatable, useful jQuery extension, we
could write
$.fn.getClassNames = function() {
if (name = this.attr("className")) {
Command syntax: hasClass
hasClass(name)
Determines if any element of the matched set possesses the passed class name
Parameters
name
(String) The class name to be checked
Returns
Returns true if any element in the wrapped set possesses the passed class name;
false
if not


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.