This question already has answers here:
Find an element in DOM based on an attribute value
(11 answers)
Closed 8 years ago.
I am looking for a method like document.getElementsByClassName(), but just for attributes, that would also mean that document.getElementsByAttributeValue("class", "testclass") would have the same output as document.getElementsByClassName("testclass").
It is not that easy since you cannot just add a function like this
document.getElementsByAttributeValue = function(){....};
because it has to work for document.getElementById("foo").getElementsByAttributeValue(...) as well.
Needless to say, that I don't want a JQuery solution because there is no need for a giant library for just one function.
The function I created and the implementation looks like this:
Node.prototype.getElementsByAttributeValue = function(attribute, value){
var dom = this.all || this.getElementsByTagName("*");
var match = new Array();
for (var i in dom) {
if ((typeof dom[i]) === "object"){
if (dom[i].getAttribute(attribute) === value){
match.push(dom[i]);
}
}
}
return match;
};
I wanted the function to work within every html element and in the html document as well, so I added the function to the parent class of all html subclasses, the Node class.
There is a nice visualisation of JavaScript objects.
With this.all || this.getElementsByTagName("*") I took all the html elements within the object which called the function. Then I looped through all the elements I took and checked if they had the right attribute values and if they had, I pushed them into the match array
You can use JQuery to easily get all the elements with a particular class as follows:
$('[class~="d1"]')
This will select the elements with class containing d1
Check Demo
For more: Read JQuery selector
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
I know I've seen a beautifully straightforward answer to a similar question before, but I haven't been able to remember or locate it, so apologies in advance.
I'm not new to coding, but I've had no formal training with Javascript/jQuery. Everything else I used has been strictly typed, so I'm still struggling with how JS does typing. I have a function that fires every time a child of a specific class is changed (I'm writing this for Sharepoint, so there is some working-around that has to be done.)
Why is it when I write this:
$(".listen *").change(function(event) {
var element = event.target;
if (element.title == 'Workstation')) {
alert(element.val());
}
}
I get an error that .val() is not a function, and I have to instead write
$(".listen *").change(function(event) {
var element = event.target;
if (element.title == 'Workstation')) {
alert($('#' + element.id).val());
}
}
What is the difference between the object that "element" is and the object retrieved by using the id? Aren't they both jQuery objects? I realize that not all objects returned by my function might actually have a value to return, but I don't understand how the distinction is being made.
Thanks!
In your first code block the 'element' variable is not a jQuery object, it is a DOM object. The .val() method is not defined for DOM objects. It is only defined for jQuery objects.
In your second code block $('#' .element.id) returns a jQuery object that does have the val() method defined.
So to answer your question, No they are not both jQuery objects, only the second one is.
You must make jQuery object from your dom (event.target) like that;
$(".listen *").change(function(event) {
var element = $(event.target);
if (element.attr('title') == 'Workstation')) {
alert(element.val());
}
}
Then you can use your jQuery object as you want. By the way, if you want to catch the changed element, you can use $(this) instead of $(event.target).
$(".listen *").change(function(event) {
var element = $(this);
if (element.attr('title') == 'Workstation')) {
alert(element.val());
}
}
This question already has answers here:
How can I check if an element exists in the visible DOM?
(27 answers)
Closed 8 years ago.
The question is quite straightforward. Is there a javascript only (no jQuery/other library pls) method of checking if an element created via javascript exists?
For instance, if I did this:
var foo=document.createElement("div");
document.getElementById("bar").appendChild(foo);
Would there be a way to check if foo already exists?
You could simply get the element by id and see if its not null.
var foo=document.createElement("div");
document.getElementById("bar").appendChild(foo);
foo.setAttribute("id","foo");
var ele = document.getElementById("foo");
if(ele !== null){ alert("Hi");}
foo is not an element, it's a variable whose value is an element. There are different ways to interpret your question.
Is the value of the variable foo a DOM element?
If you want to check if the variable foo exists and has as its value an element, you can say
foo && typeof foo === 'object' && foo.nodeType
or something similar. This will check whether the element is any kind of Node. To check for an element, use foo.nodeType === Node.ELEMENT_NODE.
Is a particular HTML element in the DOM?
If you want to check if the element held in variable foo is in the DOM, as opposed to having been created, but not yet inserted, then:
foo.baseURI
since baseURI is set only upon DOM insertion. You might think you could check parentNode, which is also not set until DOM insertion, but children of the non-inserted element, if any, will report a parentNode, as will elements appended to a document fragment.
The other alternative is to use Node#contains:
document.body.contains(foo)
which essentially does the same thing as scanning the entire DOM for the element:
Array.prototype.some.call(document.querySelector('*'), function(elt) {
return elt === foo;
})
In any case, this all seems pointless, because as far as I can imagine, if you hold a reference to a DOM element, and it's not not in the DOM, then it is in the DOM.
Is there already an element in the place I'm going to be inserting this one?
If you know where the element is going to go, in this case as a child of bar, and that's enough to convince you that the "element already exists", you can check easily enough with something like:
document.getElementById("bar").children.length > 0
Is there already an element with this ID?
As other commenters and responders have noted, you can obviously find an element in the DOM if you have arranged to provide it with some uniquely identifiable characteristics, most likely an id.
I hope it's obvious that element ID is completely separate from the name of any JavaScript variables which happen to be holding references to that element. It is true that elements become available on the root (window) object under their ID or name attributes, a feature best left unused.
Was the element in the source HTML, or created by JavaScript?
From the wording of your question, it seems that you might be interested in whether the element was created by JS, as opposed to originating from the source HTML. There is no way I know of to detect that. If you are intent on doing so, override document.createElement as follows:
document.createElement = (function() {
var old = document.createElement;
return function(tagName) {
var elt = old.call(document, tagName);
elt.I_CREATED_THIS = true;
return elt;
};
}());
> document.body.I_CREATED_THIS
undefined
> elt = document.createElement('span');
> elt.I_CREATED_THIS
true
This question already has answers here:
Get an element by index in jQuery
(5 answers)
Closed 8 years ago.
I'm trying to set a .click function for the first element with a certain class - and each one will need separate code, incrementing my purchase function, with the first one using purchase(0,0,1); and the second using purchase(0,1,1); and so forth. While doing so with $(".generation:first") (with generation being said class) works, I want to be able to do this for all elements with this class, referring to them from an array, and for some reason
$(".generation")[0].click(function () { purchase(0,0,1); });
doesn't work - no errors or anything. It just doesn't seem to select it. Just the same later:
// Note: listings is an array of three different classes, 0 is .generation
// Therefore, 'listings[0][0]' should be identical to '$(".generation")[0]'
listings[0][0].find(".count").text(game.buildings[type][id].count+" bought");
The above won't work, stating undefined is not a function, if I use .children(".count") it instead says object is not a function.
You use .eq(0) to get the first element in a jQuery object. [0] just gets you the first DOM object which obviously doesn't support the jQuery .click() method of adding an event handler. So, you can do it like this:
$(".generation").eq(0).click(function () { purchase(0,0,1); });
If you want slightly different functionality for each .generation element as your comments now indicate, you can iterate with .each() and do something slightly different on each element.
$(".generation").each(function(index) {
$(this).click(function() {
purchase(0, index, 1);
});
});
You can just call the click function on the jQuery object to register the handler for all elements with the said class
$(".generation").click(function () { purchase(0,0,1); });
The problem is the .click() function is present in the jQuery object, but when you use $(".generation")[0] it returns a dom element reference which does not have the method thus you are getting the error.
In that case, you can find the index of the current element like
var $els = $(".generation").click(function () {
purchase(0, $els.index(this), 1);
});
With jquery, I've got the following code:
$('a[data-hello]').click(function(){ = That select all "a" elements with "data-hello".
I'm trying to make this with raw Javascript. I stop here:
document.querySelectorAll("data-hello").onclick = function() {
(btw, theres a way to select all the A elements with data-hello and not all with data-hello? o.O)
But querySelectorAll returns a Array. Because of this, it only works if I determine a position. This way:
document.querySelectorAll("data-hello")[5].onclick = function() {
But I want ALL ELEMENTS, not specific elements, like with jQuery. I cant use jQuery.
It is so simple with Jquery :( I must make a "for" to wade through all the positions in JS? Is this necessary? sorry I do not understand...
What I want to do:
I want to get the data attribute value of the element that is clicked. I use this for this inside the function and, then, I applied another function that add a class in a specific element.
Basically, there is buttons with classes in data attribute value. This classes will be applied to a specific element.
Put the array (actually a NodeList) of elements in a variable and loop through them to set the event handler on each of them. That's what the jQuery methods do to apply something to all elements in a jQuery object. There is no way around the loop, with jQuery it's just hidden within the methods. You can use the same selector syntax as in jQuery with querySelectorAll.
var arr = document.querySelectorAll("a[data-hello]");
var f = function() {
// do something
};
for (var i = 0; i < arr.length; i++) {
arr[i].onclick = f;
}
querySelectorAll accepts a string of comma-separated CSS selectors, just like jQuery, so you can give it the same string: 'a[data-hello]'.
The difference between native and jQuery that you are running into is in calling methods on the elements returned. jQuery returns a jQuery object, which has methods that often loop over all the elements, .click() being one such methods. You need to replicate that with the array of elements that querySelectorAll is returning by looping over the array and applying the same handler to each element's onclick property.
Try this:
var myElements = document.querySelectorAll("a[data-hello]");
Array.prototype.forEach.call(myElements, function (element) {
element.onclick = function () {
// Your onclick handler code goes here.
console.log('clicked', element);
};
});
as simple as that:
var dataElems = document.querySelectorAll("[data-hello]")
for (var i=0;i<dataElems.length;i++) {
dataElems[i].onclick = function(i,v) {
alert(this.innerHTML)
}
}
example http://jsfiddle.net/acrashik/W86k8/