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?
相关问题
- Laravel Option Select - Default Issue
- How to fix IE ClearType + jQuery opacity problem i
- jQuery add and remove delay
- HTML form is not sending $_POST values
- How to use Control.FromHandle?
I beleive
or
should do the trick...
I think you can find all the core functions in the jQuery Docs, although I hate the formatting.
Another option, if you prefer, would be to get the DOM element from the jQuery object and use standard DOM accessors on it:
The "jQuery way", as mentioned by others, is to use the attr() method. See the API documentation for attr() here.
In jquery ui modal dialogs you need to use this construction for some reason:
for first title:
https://github.com/ertaserdi/jQuery-Title
If you are creating a
div
and trying to add atitle
to it.Try
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
title
does indeed exist as a read/write property on manyHTMLElement
s, 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
title
property without jQuerySince
title
is 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
title
property with jQuery (v1.6+)jQuery introduced a new method in v1.6 to get and set properties. To set the
title
property 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
title
attribute with jQuery (versions <1.6)You can change the
title
attribute with the following code:Or retrieve it with:
Check out the
attr()
API documentation for jQuery.