I have this code in the source code of the page:
<a data-toggle="dropdown" class="user" href="#">Tom</a>
I tried to parse the string "Tom" with this code:
var username = document.getElementsByClassName("user").innerHTML;
alert(username);
But the username variable was undefined, what is the problem with the code?
I don't want to use jQuery.
Look at the name of the DOM method: getElement*s*ByClassName. It's a plural, so can, and most likely will, return more than 1 element.
These elements will be stored in a array like object (instance of NodeList).
var usernames = document.getElementsByClassName('user');
var first = usernames[0];
But really, getElementsByClassName is not as well supported, it would be preferable to use querySelectorAll (compare the querySelector support support with that of the getElementsByClassName, especially in IE)
var usernames = document.querySelectorAll('.user');
var first = usernames[0];
Besides, using these selectors, you can bypass having to query the entire DOM:
var username = document.querySelector('.user');//gets just one
Note:
Details on the NodeList class on MDN here
Do note that some versions of FireFox will return an object that is not called NodeList, but Mozilla's own superset of the DOM API, which extends the NodeList constructor. I can't recall what that object is called ATM, but I'll get back in touch once I remember
You just missed the [0] to get the first element.
var username = document.getElementsByClassName("user")[0].innerHTML;
Unlike document.getElementById, the document.getElementsByClassName method returns an array of elements which have your specified class. In this case, you might want to pick the first of them.
var username = document.getElementsByClassName("user")[0].innerHTML;
alert(username);
You have missed [0].
Related
This question already has answers here:
How to Get Element By Class in JavaScript?
(12 answers)
Closed 9 years ago.
Using JavaScript, we can get element by id using following syntax:
var x=document.getElementById("by_id");
I tried following to get element by class:
var y=document.getElementByClass("by_class");
But it resulted into error:
getElementByClass is not function
How can I get an element by its class?
The name of the DOM function is actually getElementsByClassName, not getElementByClassName, simply because more than one element on the page can have the same class, hence: Elements.
The return value of this will be a NodeList instance, or a superset of the NodeList (FF, for instance returns an instance of HTMLCollection). At any rate: the return value is an array-like object:
var y = document.getElementsByClassName('foo');
var aNode = y[0];
If, for some reason you need the return object as an array, you can do that easily, because of its magic length property:
var arrFromList = Array.prototype.slice.call(y);
//or as per AntonB's comment:
var arrFromList = [].slice.call(y);
As yckart suggested querySelector('.foo') and querySelectorAll('.foo') would be preferable, though, as they are, indeed, better supported (93.99% vs 87.24%), according to caniuse.com:
querySelector(all)
getElementsByClassName
Don't use w3schools to learn something
Refer to MDN for accurate information
Another option is to use querySelector('.foo') or querySelectorAll('.foo') which have broader browser support than getElementsByClassName.
http://caniuse.com/#feat=queryselector
http://caniuse.com/#feat=getelementsbyclassname
You need to use the document.getElementsByClassName('class_name');
and dont forget that the returned value is an array of elements so if you want the first one use:
document.getElementsByClassName('class_name')[0]
UPDATE
Now you can use:
document.querySelector(".class_name") to get the first element with the class_name CSS class (null will be returned if non of the elements on the page has this class name)
or document.querySelectorAll(".class_name") to get a NodeList of elements with the class_name css class (empty NodeList will be returned if non of. the elements on the the page has this class name).
you can use
getElementsByClassName
suppose you have some elements and applied a class name 'test', so, you can get elements like as following
var tests = document.getElementsByClassName('test');
its returns an instance NodeList, or its superset: HTMLCollection (FF).
Read more
So I have the following code
var email = row.cells[2];
console.log(email);
and that returns <td>jh#hotmail.com</td>as an object I think however I need that value as a string in order to remove the <td></td> I some websites says that I can use JSON.stringify but when i do it like that it returns {} anybody knows why?.
The value that is returned is not just a normal JavaScript object, it's a special one. It is a DOM node, or more specifically a DOM element. It is the way the page is represented in JS.
Because of this, JSON.stringify() returns {}. Luckily, DOM elements have their own way of getting contents. To get the text content of a DOM element, use .textContent. In this case, it would be
var DOM_Element = row.cells[2];
var email = DOM_Element.textContent
console.log(email);
Consider also innerHTML
var email = row.cells[2].innerHTML
console.log(email);
Credit to #vlaz's comment.
try
var email = row.cells[2].textContent;
I have a class as
<div class="group-left article_left">
I need to add a id for this class dynamically using JavaScript.
i have added the following code
var thediv = document.getElementByClass("#group-left");
thediv.id = "pad_id";
But the id is not appearing in my code.Can anyone help me.
The method is called getElementsByClassName and returns a NodeList, not a single node (so you need to treat it as an array and either loop over it or just grab the first element from it).
You also need to spell your class name correctly. You don't have a # character in it.
var thediv = document.getElementsByClassName("group-left")[0];
thediv.id = "pad_id";
It isn't supported by Internet Explorer 8 or lower so you may wish to use a polyfill or a library (such as YUI or anything else implementing a selector engine) with equivalent functionality instead.
There is now getElementsByClass method in javascript unless you use some library. You can use jquery
$('.class').attr('id','pad_id');
You should only use one id per element though. Remember that
You have to use setAttribute, like such:
thediv.setAttribute("id", "pad_id");
I am trying to make a bookmarklet that will return a user id for a website i am registered for. When logged into the website there is a piece of code as follows:
<input id="memberID" name="00V85345345343ugFFC" type="hidden" value="3959721"/>
This is the JavaScript i am using but it doesnt do anything. AmI doing something wrong here?
javascript:alert("Your member ID is\n"+document.getElementById("memberID")[0].value);
document.getElementById returns a HTMLElement or null if no element was found matching that ID.
Because element ID's are supposed to be unique, it makes no sense to return an Array; a maximum of one element should be matched.
javascript:alert("Your member ID is\n"+document.getElementById("memberID").value);
document.getElementsByTagName however, for example (note the plural of elements, rather than element), returns an array of elements; as it makes perfect sense to have more than one element of the same tag in a page.
var divElements = document.getElementsByTagName("div");
if (divElements.length) {
var firstElement = divElements[0];
};
getElementById returns single element, not array of elements.
So this:
getElementById("memberID")[0].value
Must become just:
getElementById("memberID").value
Maby this will help abit in cleaning up that error:
http://p-xr.com/jquery-like-getelementbyid-in-1-line-of-code/
How do I get an element or element list by it's tag name. Take for example that I want all elements from <h1></h1>.
document.getElementsByTagName('a') returns an array. Look here for more information: http://web.archive.org/web/20120511135043/https://developer.mozilla.org/en/DOM/element.getElementsByTagName
Amendment: If you want a real array, you should use something like Array.from(document.getElementsByTagName('a')), or these days you'd probably want Array.from(document.querySelectorAll('a')). Maybe polyfill Array.from() if your browser does not support it yet. I can recommend https://polyfill.io/v2/docs/ very much (not affiliated in any way)
Use $$() and pass in a CSS selector.
Read the Prototype API documentation for $$()
This gives you more power beyond just tag names. You can select by class, parent/child relationships, etc. It supports more CSS selectors than the common browser can be expected to.
Matthias Kestenholz:
getElementsByTagName returns a NodeList object, which is array-like but is not an array, it's a live list.
var test = document.getElementsByTagName('a');
alert(test.length); // n
document.body.appendChild(document.createElement('a'));
alert(test.length); // n + 1
You could also use $$(tag-name)[n] to get specific element from the collection.
If you use getElementsByTagName, you'll need to wrap it in $A() to return an Array. However, you can simply do $$('a') as nertzy suggested.