jQuery - get content and attributes

Get content - text(), html() and val()

Three simple and useful jQuery methods for DOM manipulation:

  • text() - sets or returns the text content of the selected element
  • html() - Sets or returns the content of the selected element (including HTML markup)
  • val() - set or return the value of the form field

example

$("#btn1").click(function(){
  alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
  alert("HTML: " + $("#test").html());
});


Get attribute - attr()

The jQuery attr() method is used to get the attribute value.

The following example shows how to get the value of the href attribute in a link:

example

$("button").click(function(){
  alert($("#www").attr("href"));
});


Set content - text(), html() and val()

Setting content:

  • text() - sets or returns the text content of the selected element
  • html() - Sets or returns the content of the selected element (including HTML markup)
  • val() - set or return the value of the form field

example

$("#btn1").click(function(){
  $("#test1").text("Hello world!");
});
$("#btn2").click(function(){
  $("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
  $("#test3").val("Dolly Duck");
});

Callbacks for text(), html() and val()

The three jQuery methods above: text(), html() and val() also have callbacks. The callback function takes two parameters: the index of the current element in the list of selected elements, and the original (old) value. Then return the string you wish to use with the new value of the function.

example

$("#btn1").click(function(){
  $("#test1").text(function(i,origText){
    return "Old text: " + origText + " New text: Hello world!
    (index: " + i + ")";
  });
});

$("#btn2").click(function(){
  $("#test2").html(function(i,origText){
    return "Old html: " + origText + " New html: Hello <b>world!</b>
    (index: " + i + ")";
  });
});























Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325089271&siteId=291194637