JQuery Get Attributes are very powerful and useful topic. It is very useful because by using this functionality we can manipulate the DOM.
JQuery given us a numerous number of predefined functions to get access of DOM elements and also manipulate the DOM elements and attributes.
The following are the four important methods to manipulate the DOM.
- text()
- attr()
- val() and
- html()
jQuery Get Attributes text() :
This text() method is used to combine text contents of the elements or it is also used to set the text value to the element.
$("p").click(function() { $("target").text("Sample String"); });
jQuery Get Attributes attr() :
It is used to get the attribute or set the attribute of the element.
<input type="text" name="onlinetutorialspoint"></input> $(document).ready(function() { $("input").attr("name"); });
On the above example, I am trying to get the name attribute value for input element.
jQuery Get Attributes val() :
It is used to get the current value or set the current value of the element.
<input type="text" value="onlinetutorialspoint"></input> $(document).ready(function() { $("input").val(); });
On the above example, I am trying to get the value attribute value for input element. For this we can get onlinetutorialspoint as output.
jQuery Get Attributes html() :
It is used to get the html contents or set the html contents of the element.
<div id="input"> <input type="text" value="10"></input> <button>Toggle..</button> </div> $(document).ready(function() { alert($("#input").html()); });
For the above example, we can get the below html code as output.
<input type="text" value="10"></input> <button>Toggle..</button>
Happy Learning 🙂