Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
brandonlind2
7,823 PointsI'm confused on the differences between .attr() and .val()
from my understanding .attr() and .val() are the same except .attr() returns the origanl value/ the value in the markup were as the .val() returns the current value. I did a little experiment
var attrib=$('#overlay').attr('style');
//returned the initial value "display: none;"
//then I changed the value with
var test= $('#overlay').attr('style', 'display: block');
// returned "display: block;"
//I then pulled back up the value with .attr()
var test2= $('#overlay').attr('style');
// returned "display: block;", it returned the current value not the one in the markup
so what is the difference I'm not seeing it, could someone please explain what it is I'm missing
2 Answers
Marco Amadio
4,882 PointsHi!
The attr(attribute) method returns the value of attribute e.g.
$("#img").attr("src");
/* Will return the value of the element with id "img" */
Else, attr(attribute, value) will assign the value to the attribute
$("#img").attr("src", "http://foo.bar");
/* Will set the attribute "src" of the elment with id "img" to "http://foo.bar" */
The val() method works similar to attr() method, but it returns the value of value attribute, or assign a value to it e.g.
$("#myInput").val(); /* returns the value assigned to "value" attribute of the element with id "myInput" */
$("#myInput").val("foo"); /* assigns the value "foo" to the "value" attribute of the element with id "myInput" */
Hope it helps
Marco Amadio
4,882 PointsSorry for the delay.
If you use .attr("value"), you'll get value's initial value. If you use .val(), the value will update every time you'll edit this property.
I've created a little example on codepen: val() vs attr()
Try to edit the fields content, then click on the buttons to see the difference.
brandonlind2
7,823 Pointsbrandonlind2
7,823 Pointsthanks! that helps bit, why not use
?