Learn JQuery Step By Step Part 4: Attributes

JQuery makes it insanely easy to manipulate all attributes of HTML tags. This means that you can dynamically assign attributes with their values to any tag in html. Attributes have the same syntax as effects and events.

Let’s take a look at what you can do with some attribute functions.

attr( properties )

This function let’s you add attributes to tags with their values.

Let’s make an img tag without any attributes

<img />

Now let’s assign the src, alt and title attributes using with JQuery using attr.

$("img").attr({
  src: 'ugly-duckling.png',
  alt: 'duck',
  title: ' a duck'
});

You can see that the syntax for this function is the name of an attribute followed by its value. If you want more attributes use a comma to separate each attribute-value pair.

The next attributes are two that I use the most when am making forms.

html(val) and val()

html() refers to the HTML content of a tag, you can put a string of content for val and it will replace the HTML of the selector you specify with that string. This is just like using innerHTML in regular Javascript.

val() gets the value of form fields.

Let’s make a script that takes the value in a text area tag and puts it in a division as the user is typing. We’ll be the event keydown for this.

The HTML

<textarea>

</textarea>
<div>
</div>

The JQuery Code

$("textarea").keydown(function(){
    // when the users presses a key
    $("div").html($("textarea").val());
});

You could also assign the value of the text area to a variable and use that variable for the html.

var text;
$("textarea").keydown(function(){
    // when the users presses a key
    text=$("textarea").val()
    $("div").html(text);
});

The last attribute am about to show you is one that adds a class to a tag. The class refers to a CSS class with some style.

addClass( class )

The function definition is pretty self explanatory I think. If you made a CSS class called "error" and you wanted to add it to a div when the users clicks a button you would do the following.

$("button").click(function(){
    $("div").addClass("error");
});

I covered almost every attribute but the full list is worth checking out.

blog comments powered by Disqus