JS how to get twitter's name [duplicate] - javascript

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

Related

element.className only returns "undefined"

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))

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"]')

javascript parsing not working document.getElementsByClassName

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].

why does $('el')[0].className work but not $('el').className?

I noticed that className property doesn't work inside jQuery without the index, why is that?
Also, are there other common JS properties / methods that don't work as expected inside jQuery?
HTML:
<div class="par">test</div>
JQuery:
$(function () {
var el = $('.par');
el.className += ' new class'; // doesn't work
el[0].className += ' new class'; // works
});
var el = $('.par'); returns a jQuery object. className is a property on Element and not on jQuery object.
The jQuery object has an array like definition so el[0] returns the underlying Element which has className property.
As far as I know, jQuery doesn't like developer updating its property directly. It simply exposes variety of utility functions for easy developement.
Quoting on a nice comment from David Thomas below,
jQuery methods can only be used on jQuery objects; native DOM properties/methods can only be used on native DOM nodes
Note: var el = $('.par'); returns a collection of Element and el[0] returns the first element in that list.
You could use .addClass to add a class to the element.
To the first element,
el.eq(0).addClass('new_class');
To all elements,
el.addClass('new_class');
More Reading:
https://developer.mozilla.org/en-US/docs/Web/API/element
https://developer.mozilla.org/en-US/docs/DOM/element.className
var el = $('.par');
gives you a jQuery object, which may contain one or more DOM elements.
var el = $('.par')[0];
returns the first DOM object in the selection of that jQuery object. className is a property on a DOM element, not on a jQuery object
$('.par').attr('class');
would be the jQuery way to get the className of the first element.
If you just want to add a particular class to elements matching another class, you can use
$('.par').addClass('testclass');
This will add the test class to all elements with the par class, while your method will only add it to the first element on the page.
Other properties
Also, are there other common JS properties / methods that don't work as expected inside jQuery?
Most dom properties will not work directly on a jQuery object. You can use [0] to get the raw dom element for the first matched element for those. However most of them also have straightforward equivalents in jQuery. The advantage of using the jQuery versions is that they're often simpler, and work consistently across browsers. Native dom properties tend to be faster to access though.
className is part of the api for a DOM element.
var el = $('.par'); will return a jQuery object with an array of elements.
Using el[0] accesses the first element which has access to the api.
jQuery provides an easy method for adding classes to an element or group of elements matched by a selector called addClass. You could use this:
var el = $('.par');
el.addClass('new class');
Also note that it is usually best practice to name variables which contain a jQuery object with $ like this:
var $el = $('.par');
The jQuery DOM object is actually a list of matching elements. Since you're setting a variable on a list of DOM elements, jQuery can't apply them to the entire list. el[0] is the first matched element. (If you have more than one element, using el[0] will only set the first matched element, and if there aren't any matches, el[0] will raise a ValueError.) You should probably use jQuery's builtin class manipulation functions:
el.addClass("new class");
to remove the classes:
el.removeClass("new class");
and to toggle them:
el.toggleClass("new class");
This might not be directly related to the question, but if you're working with jQuery, then you should also be using jQuery's easy to use methods to modify the classname's of all DOM elements within a jQuery object.
http://api.jquery.com/addClass/
http://api.jquery.com/toggleClass/
http://api.jquery.com/removeClass/
$(function () {
var cname = $('.par').attr('class'); // get class attribute
if (!$('.par').hasClass('some-new-class')) {
$('.par').addClass('some-new-class');
}
});

Removing $() jQuery wrapper to just get raw JS element [duplicate]

This question already has answers here:
How to get a DOM Element from a jQuery selector?
(4 answers)
Closed 8 years ago.
Random just out of curiosity question:
Let's say for whatever reason I get an element back from a function
$(element)
But I want to remove the $( __ ) jQuery wrapper to leave the regular DOM Element:
element
Is this possible? (I'm sure it'd be smart to test $(element).length() to make sure it isn't more than 1 thing inside beforehand too...
jsFiddle
var firstElem = $(element)[0];
or
var firstElem = $(element).get(0);
Calling get() without an index gives you an array of the elements.
Reference: jQuery get()
DOM elements are stored as properties at numeric zero-based indices, so you access them just like you would for any other object.
$jqObj[0];
Or get a full Array of elements using toArray()
$jqObj.toArray();
Fiddle: http://jsfiddle.net/xHj5d/2/
removeJWrapper($('#ohHeyo'));
function removeJWrapper (el) {
console.log(el[0]);
}

Categories

Resources