Saturday, 26 March 2016

Getting and setting contents and attributes in jQuery ?


Getting Contents

We can use jQuery methods for DOM manipulation.
text() : Sets / returns the text content of selected elements.
html() : Sets / returns the content of selected elements. (including HTML markup)
val() : Sets / returns the value of form fields.

Example 1. Using text()
$("#button1").click(function() {
  alert("Text :  " + $("#test").text());
});

Example 2. Using html()
$("#button2").click(function() {
  alert("HTML: " + $("#test").html());
});

Example 3. Using val()
$("#button3").click(function() {
  alert("Value: " + $("#test").val());
});



Getting Attributes

attr() - Gets attribute values.

Example
$("button4").click(function() {
  alert($("#test").attr("href"));
});



Setting contents and attributes

Example 1. Setting text content of selected elements
$("#btn1").click(function() {
  $("#test1").text("Hello world!");
});

Example 2. Setting content of selected elements including markup
$("#btn2").click(function() {
  $("#test2").html("<b>Hello world!</b>");
});

Example 3. Setting value of form fields
$("#btn3").click(function() {
  $("#test3").val("Dolly Duck");
});

Example 4. change / set the value of attribute
$("button1").click(function() {
  $("#test").attr("href","http://www.geniusprog.com");
});

Example : Set multiple attributes - using JSON
$("button1").click(function() {
  $("#test").attr({
    "href" : "http://www.geniusprog.com",
    "title" : "Genius programmers"
  });
});

No comments:

Post a Comment

Note: only a member of this blog may post a comment.