element.className only returns "undefined" - javascript

I'm trying to make a little interactive gallery in which people could check/select some picures. I used some to contain the pictures and add some in there to indicate selected photographs. Then I typed a little JS code to check or uncheck photographs using the className of the .
So my two problems are :
The code doesn't run as expected. Can't select any picture when I'm runnin' my navigator.
The console only returns "undefinded" as explain in the code below.
Here's some code :
It's kind of my first attempt in JS and I don't really understand what isnt's not working so I hope you'll got an answer or at least some little indications for me. :)
Thanks,
Thomas

As mentioned in previous answers the getElementsByClassName method returns a HTMLCollection of elements that have the class name that you pass to the method. If you need to access any of the items, you will need to do it like an array.
For example, getting the first element of the collection.
unselectedClass[0].className;
Otherwise you could use a for loop to access each element in the collection.
for (var i = 0; i < unselectedClass.length; i++) {
var class = unselectedClass[i].className;
}

getElementsByClassName yields a collection of elements. The className property is available on a specific element in that list. Not on the list itself.

The problem is that document.getElementsByClassName returns HTMLCollection and HTMLCollection. You should check the className of its elements.
You can loop through it then get className of each element
for(let i = 0;i<unslectedClass.length;i++){
console.log(unselectedClass[i].className);
}
Or convert the HTMLCollection to a real array using Spread Operator and use forEach()
[...unselectedClass].forEach(x => console.log(x.className))

Related

JS how to get twitter's name [duplicate]

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

Get the ID of an element where the class contains a given string

I am currently trying to figure out a way to get the ID of an element, depending on whether its class contains something. I'm not sure if there's a better way to do it than I currently am, but having looked around nothing fits exactly the need I have. The code I currently have is, where I am looking for a div element whose class contains the string "one" but is not limited to that. Currently there is only one element containing this string but the alert provides me with [Object NodeList] (I may well be overcomplicating this):
$idToMove = document.querySelectorAll('div[class^="one"]');
alert($idToMove);
document.querySelectorAll() Returns a node list (kind of like an array), if you are sure there will only ever be one you have a couple options.
1) Use .querySelector instead:
// returns the first node that matches
var elm = document.querySelector('div[class~="one"]');
console.log(elm.id);
2) Access the first element in the returned list:
// returns all nodes that match
var elms = document.querySelectorAll('div[class~="one"]');
console.log(elms[0].id);
Make sure to null check returns of .querySelector and length check returns of .querySelectorAll.
Notice also, that I use ~= and not ^=. You can read on the MDN about the difference between all the equality operators. But for these two:
[attr~=value]
Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly "value".
[attr^=value]
Represents an element with an attribute name of attr and whose first value is prefixed by "value".
First get element from DOM and than from that element get id attribute:
1- If you need only first element then use querySelector like this:
let elms = document.querySelector('div[class~="one"]')[0].id
console.log(elms)
2- If you need all element those have this class then use querySelectorAll like this:
let elms = document.querySelectorAll('div[class~="one"]')
for(let i=0; i<elms.length; i++)
{
console.log(elms[i].id)
}
I think with "*" it works in more cases
document.querySelector('div[class*="words"]')
i tried it works absolutely amazing
window.frames[0].document.querySelector('td[id*="sss"]')

How to select multiple ID's in a badly designed webpage?

I am maintaining a complex web application.
I have a large number of divs which all have the same ID.
I know this is totally wrong, and as a matter of fact document.getElementById() with that id is going to only produce one match for me.
However I am able to pull out the element that I'm looking for using jQuery (we are on 1.6.2), like this: $('#bad_id[nonstandard_attr_name=somethingSpecific]')
Not quite ready to say that this is a "solution".
I'm worried about whether this is reliable or not. Is jQuery really actually gonna search through all the elements that match the ID using a DOM walk? That's probably the only way to get all of them.
Does it filter elements by the other attribute first, and then filter it down by the ID? That would achieve the desired behavior as well, but it would be good to know the order it does this in.
If you need to select multiple elements with same id you can simply use an attribute selector:
$( "[id='myid']" )
The attribute selector doesn't look at the attribute key for any semantics like unique ids or such.
http://jsfiddle.net/ZWm3G/
I cannot tell you what jQuery or other dom traversals will do (doubtful it will work always) but you can try this :
document.filter = function(attr, val, r) {
r = r || document.getElementsByTagName("*");
var s = [];
for(var i = 0; i < r.length; i++) {
if(r[i].getAttribute(attr) == val) {
s.push(r[i]);
}
}
return s;
};
var s = document.filter("nonstandard_attr_name", "somethingSpecific", document.filter("id", "bad_id"));
console.log(s);
http://jsfiddle.net/KGPFf/1/
Well, as seen in comments, my guess was why would it go on searching for any element. Yes
getElementById returns the first element and then stops searching, but the same doesn't look right for jQuery. It does return all the elements with that "bad" id.
As can be seen in this Fiddle,
So it is selecting all the elements, this means jQuery doesn't stop at the first element, but goes on searching the entire doument, hence IMO, you may use jQuery to select multiple elements with the common id. There shouldn't be any problem.
Use a selector that will result in something other than getElementById() being used should result in consistent results, but make sure you test it with IE8 since IE8 doesn't use document.querySelectorAll().
Using methods such as .find .children and .filter should also yield consistent results regardless of the id being unique.
Sample: http://jsfiddle.net/gb3Mz/

problem with javascript getElementById that is hidden

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/

getElementById() wildcard

I got a div, and there i got some childnodes in undefined levels.
Now I have to change the ID of every element into one div. How to realize?
I thought, because they have upgoing IDs, so if the parent is id='path_test_maindiv' then the next downer would be 'path_test_maindiv_child', and therefore I thought, I'd solve that by wildcards, for example:
document.getElementById('path_test_*')
Is this possible? Or are there any other ways?
Not in native JavaScript. You have various options:
1) Put a class and use getElementsByClassName but it doesn't work in every browser.
2) Make your own function. Something like:
function getElementsStartsWithId( id ) {
var children = document.body.getElementsByTagName('*');
var elements = [], child;
for (var i = 0, length = children.length; i < length; i++) {
child = children[i];
if (child.id.substr(0, id.length) == id)
elements.push(child);
}
return elements;
}
3) Use a library or a CSS selector. Like jQuery ;)
In one of the comments you say:
(...) IE is anyway banned on my page, because he doesn't get it with CSS. It's an admin tool for developer, so only a few people, and they will anyway use FF
I think you should follow a different approach from the beginning, but for what it's worth, in the newer browsers (ok, FF3.5), you can use document.querySelectorAll() with which you can get similar results like jQuery:
var elements = document.querySelectorAll('[id^=foo]');
// selects elements which IDs start with foo
Update: querySelectorAll() is only not supported in IE < 8 and FF 3.0.
jQuery allows you to find elements where a particular attribute starts with a specific value
In jQuery you would use
$('[id^="path_test_"]')
Try this in 2019 as a wildcard.
document.querySelectorAll("[id*=path_test_]")
I don't think so wildcards are allowed in getelementById.
Instead you can have all the child nodes of your respective DIV using:
var childNodeArray = document.getElementById('DIVID').childNodes;
This'll give you an array of all elements inside your DIV. Now using for loop you can traverse through all the child elements and simultaneously you can check the type of element or ID or NAME, if matched then change it as you want.
You should not change ID of element to ID of other existing element. It's very wrong, so you better re-think your core logic before going on.
What are you trying to do exactly?
Anyway, to get all elements with ID starting with something, use jQuery as suggested before, if you can't it's also possible using pure JavaScript, let us know.

Categories

Resources