I have an form input element and want to change its title attribute. This has to be easy as pie, but for some reason I cannot find how to do this. How is this done, and where and how should I be searching on how to do this?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Before we write any code, let’s discuss the difference between attributes and properties. Attributes are the settings you apply to elements in your HTML markup; the browser then parses the markup and creates DOM objects of various types that contain properties initialized with the values of the attributes. On DOM objects, such as a simple
HTMLElement, you almost always want to be working with its properties, not its attributes collection.The current best practice is to avoid working with attributes unless they are custom or there is no equivalent property to supplement it. Since
titledoes indeed exist as a read/write property on manyHTMLElements, we should take advantage of it.You can read more about the difference between attributes and properties here or here.
With this in mind, let’s manipulate that
title…Get or Set an element’s
titleproperty without jQuerySince
titleis a public property, you can set it on any DOM element that supports it with plain JavaScript:Retrieval is almost identical; nothing special here:
This will be the fastest way of changing the title if you’re an optimization nut, but since you wanted jQuery involved:
Get or Set an element’s
titleproperty with jQuery (v1.6+)jQuery introduced a new method in v1.6 to get and set properties. To set the
titleproperty on an element, use:If you’d like to retrieve the title, omit the second parameter and capture the return value:
Check out the
prop()API documentation for jQuery.If you really don’t want to use properties, or you’re using a version of jQuery prior to v1.6, then you should read on:
Get or Set an element’s
titleattribute with jQuery (versions <1.6)You can change the
titleattribute with the following code:Or retrieve it with:
Check out the
attr()API documentation for jQuery.