In javascript, I would like to get the name attribute of an element.
The Mozilla Developper Network says we can use e.name or e.elementName (the latter gives undefined in Chrome for me)
This StackOverflow answer says to use e.attributes["name"].value
I guess if I tried, I'd find a few more ways.
Which way is standard-compilant ?
Which way is most compatible ?
Where can I get a list of how to access each attribute (for example, id can be accessed directly by e.id, and I'm pretty sure it's a standard-compliant way to access it) ?
To some degree it depends on the element type. The name attribute isn't supported in all element types, so it would depend on if you're using it in a valid way.
To get the value in the broadest way, use .getAttribute().
element.getAttribute("name");
If you're using name on elements that support that attribute, then I'd just use the .name property.
element.name;
Related
This seems like a simple thing, but I keep getting "undefined"
I am trying out the "data-" HTML5 attribute and I am looping through a bunch of div tags that look like this:
<div id="myEvent"
data-scheduledOn="1399985100000"
data-eventStatus="3">
And I am looping through a bunch of these like this:
$('[id="myEvent"]').each(function(index, divItem) {
alert($(divItem).data("scheduledOn"));
}
But I keep getting "undefined" If I do this (get the attribute) it works fine:
alert($(divItem).attr("data-scheduledOn"));
So What am I missing?
http://api.jquery.com/data/
"The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks."
At least at this point in time, to use the .data function you have to attach the data using the function before you can read it back using the .data function.
If you need to read pre-existing data use the .attr or .prop functions.
It seems as though It is a naming problem as Hamza Kubba suggested, but just a bit different...
if I changed the name of the data attribute to "data-scheduled-on" I can retrieve it by .data("scheduledOn") OR using data-scheduledon and .data("scheduledon") also works.
So don't use CAPS for data- names is the moral of this story!
Please note that per HTML 5 specs, the attribute name should not contain any uppercase letters and some browsers such as FF & Chrome will change any uppercase letter to lowercase. That's why the following demo works if you access the data attributes with lowercase names:
http://jsfiddle.net/fiddleyetu/5LdQd/
$('div.myEvent').each(function(index, divItem) {
console.log($(divItem).data("scheduledon"));
console.log( $(divItem).data("eventstatus") );
});
Ans since you cannot have more than one element on a page with the same ID, I have used a class selector for the demo.
MORAL: Do not use UPPERcase; your browsers may not always be that 'understanding'.
I have previously mentioned in this SO about the funny behavior for IE6/7 (and some versions of Opera) in that document.getElementById can find an element whose name attribute is defined but not the id attribute, such that
function f() {
document.getElementById("a1").value = ...;
}
...
<input name="a1" ...></input>
actually works in these versions.
Searching through the net I found this bug report by Chris Bloom, in which a user named Milo van der Leij points out the following (as referred by him in this w3c spec):
In their defense: "The id and name attributes share the same name space."
What does it mean that the id and name attributes share the same namespace? Why would this condition be sufficient for IE6/7/Opera implement this behavior in their JS engine?
The term "same namespace" means that names and ids are not completely separate. You can use the same name and id on one particular object, but you cannot use name="foo" on one object and id="foo" on another object. That creates a conflict.
It's just the way those browsers decided to implement things. There's also a global variable for each element with an id that contains the dom element. That's just the way they implemented things. It wasn't standard, it isn't the way things are done in more modern browsers (except for some backward compatibility).
Use id values for any DOM elements you want to retrieve. Use name values for server identification in posted forms.
Your code will have no conflicts between names and ids if you don't use an id on one object and the same name on another object, and there generally isn't an issue with giving a particular element the same name and id.
I've been using innerHTML and innerText for a while to change elements and text on web pages and I've just discovered that they are not W3C standard.
I've now found that innerHTML can be replaced with createElement, setAttribute and a few others but what is the best method for changing text inside an element?
I found a textContent as well but is there a standard way and is it widly implemented across older browsers?
textContent isn't implemented in IE8 and lower. You can use createTextNode() similar to how you would use createElement(). However, I often use discovery techniques to find out which property I need to use and keep a reference to it:
// You can use a shorter variable name if you want
var innerTextOrTextContent = "textContent" in document.body
? "textContent" : "innerText";
// Set an element's text:
myElement[innerTextOrTextContent] = "Added using: "+innerTextOrTextContent;
The createTextNode() example:
var tNode = document.createTextNode("Added using createTextNode()");
myElement.appendChild(tNode);
Something I often forget about, you can also directly set a text node's value, if you can get a reference to it:
// childNodes[0] is a text node:
myElement.childNodes[0].nodeValue = "Added using nodeValue";
Example - http://jsfiddle.net/BxPaG/.
I think you can't go wrong by using whatever your javascript library offers for changing text (innerHtml for jQuery). After all one of the the main reasons for using such a library is having a platform that abstracts from different browser implementations.
I want to get the name of a certain tag (to tell whether it is a div/input/span/p/so on)
I found that there are 3 different attributes that give me the tag name:
tagName, nodeName, and localName
My question is: Which one is the most supported in all browsers? And/or is there a method to get the tag name in Prototype (I looked but couldn't find one)?
nodeName is the most consistent here. I would suggest you take a minute and read this post for a few differences and inconsistencies with tagName if you're more curious as to why.
For the prototype part of the question...it's a JavaScript property, just this.nodeName should work or element.nodeName, whatever your element's called in the current function should work.
I'm trying to find a way that will add / update attribute using JavaScript. I know I can do it with setAttribute() function but that doesn't work in IE.
You can read here about the behaviour of attributes in many different browsers, including IE.
element.setAttribute() should do the trick, even in IE. Did you try it? If it doesn't work, then maybe
element.attributeName = 'value' might work.
What seems easy is actually tricky if you want to be completely compatible.
var e = document.createElement('div');
Let's say you have an id of 'div1' to add.
e['id'] = 'div1';
e.id = 'div1';
e.attributes['id'] = 'div1';
e.createAttribute('id','div1')
These will all work except the last in IE 5.5 (which is ancient history at this point but still is XP's default with no updates).
But there are contingencies, of course.
Will not work in IE prior to 8:e.attributes['style']
Will not error but won't actually set the class, it must be className:e['class'] .
However, if you're using attributes then this WILL work:e.attributes['class']
In summary, think of attributes as literal and object-oriented.
In literal, you just want it to spit out x='y' and not think about it. This is what attributes, setAttribute, createAttribute is for (except for IE's style exception). But because these are really objects things can get confused.
Since you are going to the trouble of properly creating a DOM element instead of jQuery innerHTML slop, I would treat it like one and stick with the e.className = 'fooClass' and e.id = 'fooID'. This is a design preference, but in this instance trying to treat is as anything other than an object works against you.
It will never backfire on you like the other methods might, just be aware of class being className and style being an object so it's style.width not style="width:50px". Also remember tagName but this is already set by createElement so you shouldn't need to worry about it.
This was longer than I wanted, but CSS manipulation in JS is tricky business.
Obligatory jQuery solution. Finds and sets the title attribute to foo. Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.
$('#element').attr( 'title', 'foo' );
What do you want to do with the attribute? Is it an html attribute or something of your own?
Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo" will do it.
For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo and subsequently read it without issue.