Get Content

Jquery contains predefined methods to get content and attributes of Html elements. Some predefined methods are;
  • text()
  • html()
  • val()

text() method

This method is used to set and return the text contents of selected Html element.

Example of text()

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Text: " + $("#para").text());
    });
});
</script>
</head>
<body>

<p id="para">This is my first <strong>jQuery<strong> code</p>

<button>Show text</button>

</body>
</html>

Output

This is my first jQuery code

html() method

This method is used to set and return the contents of selected Html element including Html tag.

Example of html()

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Text: " + $("#para").html());
    });
});
</script>
</head>
<body>

<p id="para">This is my first <strong>jQuery<strong> code</p>

<button>Show Html</button>

</body>
</html>

Output

This is my first jQuery code

val() method

This method is used to set and return the value of form fields. In below example you can get value from textfield.

Example of val()

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Text: " + $("#inputfield").val());
    });
});
</script>
</head>
<body>

<input type="text" id="inputfield" value="HItesh Kumar">

<button>Show Value</button>

</body>
</html>

Output