How can I get the attribute value of an element in JavaScript?
To get a NodeList of Nodes that match a selector
var list = document.querySelectorAll('[myAttribute]');
list
will be Array-like but not inherit from Array. You can loop over it with for
and list.length
To get a NamedNodeMap of the attributes on an Element
var nnm = elem.attributes;
nnm
will be Array-like but not inherit from Array. You can loop over it with for
and nnm.length
To get the value of an attribute on an Element use .getAttribute
var val = elem.getAttribute('myAttribute');
val
will be null
if there is no such attribute
To test the existance of an attribute on an Element use .hasAttribute
var b = elem.hasAttribute('myAttribute');
b
will be a Boolean value, true
or false
Getting HTML elements by their attribute names
Yes, the function is querySelectorAll
(or querySelector
for a single element), which allows you to use CSS selectors to find elements.
document.querySelectorAll('[property]'); // All with attribute named "property"
document.querySelectorAll('[property="value"]'); // All with "property" set to "value" exactly.
(Complete list of attribute selectors on MDN.)
This finds all elements with the attribute property. It would be better to specify a tag name if possible:
document.querySelectorAll('span[property]');
You can work around this if necessary by looping through all the elements on the page to see whether they have the attribute set:
var withProperty = [],
els = document.getElementsByTagName('span'), // or '*' for all types of element
i = 0;
for (i = 0; i < els.length; i++) {
if (els[i].hasAttribute('property')) {
withProperty.push(els[i]);
}
}
Libraries such as jQuery handle this for you; it's probably a good idea to let them do the heavy lifting.
For anyone dealing with ancient browsers, note that querySelectorAll
was introduced to Internet Explorer in v8 (2009) and fully supported in IE9. All modern browsers support it.
Get attribute name value of input
Give your input an ID and use the attr
method:
var name = $("#id").attr("name");
How do I retrieve an attribute's name using the nodeName property?
You can get a list of the attributes with getAttributeNames()
on the node. In your example, you could do like so:
atnode.getAttributeNames()
This will return ["href", "id"]
.
Then you can loop through the list with getAttribute(<item from list as string>)
to get the values of the element's attributes.
How to access (get or set) object attribute given string corresponding to name of that attribute
There are built-in functions called getattr
and setattr
getattr(object, attrname)
setattr(object, attrname, value)
In this case
x = getattr(t, 'attr1')
setattr(t, 'attr1', 21)
Reflection - get attribute name and value on property
Use typeof(Book).GetProperties()
to get an array of PropertyInfo
instances. Then use GetCustomAttributes()
on each PropertyInfo
to see if any of them have the Author
Attribute type. If they do, you can get the name of the property from the property info and the attribute values from the attribute.
Something along these lines to scan a type for properties that have a specific attribute type and to return data in a dictionary (note that this can be made more dynamic by passing types into the routine):
public static Dictionary<string, string> GetAuthors()
{
Dictionary<string, string> _dict = new Dictionary<string, string>();
PropertyInfo[] props = typeof(Book).GetProperties();
foreach (PropertyInfo prop in props)
{
object[] attrs = prop.GetCustomAttributes(true);
foreach (object attr in attrs)
{
AuthorAttribute authAttr = attr as AuthorAttribute;
if (authAttr != null)
{
string propName = prop.Name;
string auth = authAttr.Name;
_dict.Add(propName, auth);
}
}
}
return _dict;
}
Get attribute name of class attribute
Yes, you can make the Field
class a descriptor, and then use __set_name__
method to bind the name. No special handling is needed in MyClass
.
object.__set_name__(self, owner, name)
Called at the time the owning class owner is created. The descriptor has been assigned to name.
This method is available in Python 3.6+.
>>> class Field:
... def __set_name__(self, owner, name):
... print('__set_name__ was called!')
... print(f'self: {self!r}') # this is the Field instance (descriptor)
... print(f'owner: {owner!r}') # this is the owning class (e.g. MyClass)
... print(f'name: {name!r}') # the name the descriptor was bound to
...
>>> class MyClass:
... potato = Field()
...
__set_name__ was called!
self: <__main__.Field object at 0xcafef00d>
owner: <class '__main__.MyClass'>
name: 'potato'
How to get @Attribute name?
You are asking for class level annotations. What you want to do, is get field level annotations:
Field field = Apn.class.getDeclaredField("apnId");
Annotation[] annotations = field.getAnnotations();
Also, if you want to get specific annotation, you can use field.getAnnotationsByType(Entry.class)
, which would give you access to the specific class of the annotation and its parameters, such as name
, as you need in your case.
Related Topics
New (Std::Nothrow) VS. New Within a Try/Catch Block
Better Shading on Bw Display While Rendering Filled Surfaces
Sizeof in C++ Showing String Size One Less
C++ Error, Undefined Reference Class
What Is Linux's Native Gui API
In Cmake, How to Test If the Compiler Is Clang
Easiest Way of Using Min Priority Queue with Key Update in C++
C++ Visual Studio "Non-Standard Syntax; Use '&' to Create a Pointer to Member"
Opencv How to Select a Region of Image Irregularly with Mouse Event? C/C++
Why Calling Main() Is Not Allowed in C++
Why Can't I Do Polymorphism with Normal Variables
How to Use a String as a Variable Name in C++
Why Does Nvcc Fails to Compile a Cuda File with Boost::Spirit