Introduction with JQUERY - Accessing Content

Guest Posts Paolo Nikko Nuñal

In my previous article we tackled about JQUERY's many effects that you can apply on any HTML document. This time around, we are going to deal with JQUERY DOM Manipulation. JQUERY comes with a lot of DOM related methods that can make your life easier when changing their attributes and access. For those of you who are not familiar with the term "DOM", it stands as Document Object Model. It is a standard for accessing HTML and XML documents.




Learn HTML5/PHP/AJAX Web Programming from Scratch – An amazing course from Dr. Richard Stibbard. Usually I only promote my own courses, but this course is very impressive, so I cut a deal with Dr. Stibbard … You can also find Richard’s website here





The first thing we are going to tackle about is the text(), html() and val() methods.

text() - Is used to set or return the text content of selected elements.

html() - Is used to set or return the content of selected elements that includes HTML markup.

val () - Is used to set or return the value found on the form fields.

Here is a sample or demonstration on how you can get the content using JQUERY text () and html () methods.

Code


<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$("#btn-text").click(function(){
    alert("Get Text: " + $("#demo").text());
 });
$("#btn-html").click(function(){
    alert("HTML Code: " + $("#demo").html());
 });
</script></head>
<body>
<p id="demo">This is a <i>italic</i> and a <b>BOLD</b> text inside a paragraph.</p>
<button id="btn-text">Get HTML Text</button>
<button id="btn-html">Get HTML Code</button>
</body>
</html>


Base from the example above you can see that when we press on the "GET HTML TEXT" button, the .text() method actually returns the entire text found inside the paragraph with the id "#demo".  And whenever we clicked on the button "Get HTML Code", it returns the text as well as the html code.

The next one is the val() method, which returns whatever is inside the input box. This is useful for getting the values of forms.

Code


<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$("#btn-val").click(function(){
     alert("Value: " + $("#input1").val());
 });
</script></head>
<body>
<p>Name: <input type="text" id="input1" value=""></p>
<button id="btn-val">Get Value</button>
</body>
</html>


So everytime you click on the "GET VALUE" button, it will automatically return whatever you type on the input box.




Learn HTML5/PHP/AJAX Web Programming from Scratch – An amazing course from Dr. Richard Stibbard. Usually I only promote my own courses, but this course is very impressive, so I cut a deal with Dr. Stibbard … You can also find Richard’s website here