jQuery manipulating attributes
Posted on September 28, 2011 | Comments Off on jQuery manipulating attributes
Manipulating CSS class attribute
You can manipulate CSS class attribute using following methods :
.addClass()
You can add any css class to filtered elements through this method.
Example :
Following code add selected css class to last paragraph :
.hasClass()
Using this method , you can check any of the matched elements have provided css class or not. If it has , it will reyurn ‘True’ otherwise ‘False’.
Example :
$(‘#mydiv’).hasClass(‘foo’)
Above code checks whether the div “mydiv” have ‘foo’ css class or not.
.removeClass()
This method remove the css class from the set of matched element.
Example :
Following code will remove ‘blue’ css class from all even paragraphs :
$(“p:even”).removeClass(“blue”)
.toggleClass()
This method adds or removes a class from each element in the set of matched elements depending on either the class’s presence or the value of the switch argument.
Example :
Following code will change the css class of clicked element :
Manipulating general attributes :
Given below methods are used to get and set the Dom attributes of elements :
.attr()
This method is used to get the attribute of the first element from the matched set of elements.
Example :
Following code will get the ‘title ‘ attribute of the first matched ’em’ :
$(“em”).attr(“title”);
.removeAttr()
This method is used to remove attribute from each element of the matched set.
Example :
Consider the following code line :
The following code will enables the input next to it, on button click :
$(“button”).click(function () {
$(this).next().removeAttr(“disabled”)
.focus()
.val(“editable now”);
});
.text()
This method will get and combine the text of each matched elements by leaving their html tags.
Example :
Consider the following code :
div class=”demo-container”>
- list item 1
- list item 2
The $(‘div.demo-container’).text()will produce the following output :
Demonstration Box list item 1 list item 2
NOTE -The .text() method cannot be used on input elements. For input field text, use the .val() method.
.val( )
This method will get the current value of the first element in the set of matched elements.
Following are some example of ‘.val()’ :
$(‘select.foo option:selected’).val(); // get the value from a dropdown select
$(‘select.foo’).val(); // get the value from a dropdown select even easier
$(‘input:checkbox:checked’).val(); // get the value from a checked checkbox
$(‘input:radio[name=bar]:checked’).val(); // get the value from a set of radio buttons