Is there a way in java script to get only a particular name instead of using document.getElementsByName("x"); which return an array? I have a kind of special situation where i can’t use the id. Any suggestions please?
Thank You.
Just get the first element:
document.getElementsByName("x")[0];
Or for safety:
function getFirstElementByName(element_name) {
var elements = document.getElementsByName(element_name);
if (elements.length) {
return elements[0];
} else {
return undefined;
}
}
(BTW getElementsByName returns a collection, not an array.)
If you're looking for a single element, take the first one from the nodelist, for example:
var element = document.getElementsByName("x")[0];
You can test it out here.
Or use jQuery, so you don't have to bother with all the browser annoyance.
You just have to do this:
$("*[name='x']").first();
To get the first element with that name. If you know the element type than you can use it instead of "*". jQuery will make your life easier every time!
Related
I am trying to check if a function that is meant to be triggered by a click with a console.log but the console message never comes up
<script src="e-com.js" async></script>
this is how i linked the js file in the head
Remove
this is the link I want the event on
let removeItem=document.getElementById("remove")
for (i=0; i<removeItem.length; i++){
let remove = removeItem.addEventListener("click", function(){
console.log("Clicked");
})
}
This is the js function
The issue seems to be that you are trying to loop over the result of getElementById(), which doesn't return an iterable.
To fix it, you just need to remove the loop. The code below should work correctly^.
const removeItem = document.getElementById("remove");
removeItem.addEventListener("click", () => {
console.log("Clicked!");
});
Remove
According to MDN Web Docs:
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string.
As it states, getElementById() returns an Element, which is just an object, in short. This is why you cannot iterate over it.
If you wanted to listen to multiple objects with a for loop, you need to change a few things.
First, you can't use an id, as the id attribute is unique, and can only be used once in a HTML document. Therefore, to get multiple elements, you need to use the class attribute. See an example of the class attribute in use below.
<div class="division">Division!</div>
The class attribute can be used by any HTML element.
So, to get all of the classes and iterate over them, you need to use either the getElementsByClassName() method, or the querySelectorAll() method.
The only difference between the two is that getElementsByClassName() returns a live HTMLCollection, while querySelectorAll() returns a static HTMLCollection.
If you were to use querySelectorAll(), your code would look like this^.
const removeItem = document.querySelectorAll("remove");
Array.from(removeItem).forEach((ele) => {
ele.addEventListener("click", () => {
console.log("Clicked!");
});
});
Remove
Remove
Remove
Both of these solutions should work correctly, but they depend on what you need to accomplish.
^ The code has been modified slightly.
.getElementById() doesn't return an array since you're not allowed to have more than one element with a single id.
Therefore, the for loop failed.
Try
let removeItem=document.getElementById("remove")
removeItem.addEventListener("click", function(){
console.log("Clicked");
})
Is it possible to implement a search like document.querySelectorAll(selectors), but against an array of Node objects, rather than the entire document?
I have a pre-selected list of Node objects, and I want a function that could take the same selectors parameter, but search inside the array.
Basically, it is a question of whether or not it is possible to do a node.match(selectors) check, to verify if the node matches the selector, and then I could simply iterate through my list of nodes. But I haven't been able to find if such match-check is possible.
So I want something like this:
function querySelectorInArray(nodeArray, selectors) {
return nodeArray.filter(function(node) {
return node.match(selectors); // this line is what I want, but dunno how
});
}
Afterthought
Will it be a good idea though? I'm thinking, querySelectorAll is parsing selectors only once, but I would be doing it once for each element in the array. Will it be bad for performance? Or is there a way to avoid it, like maybe to pre-parse selectors and pass in an known object instead?
You can use Element#matches for that:
function querySelectorInArray(nodeArray, selectors) {
return nodeArray.filter(function(node) {
return node.matches(selectors);
});
}
You could simply add every node to a DocumentFragment and then use querySelector:
Documentation
I am using WebDriverIO to try to access (ie. getText, getAttribute, click, etc) an element after creating a list of elements. I am easily able to implement this element if I am using the browser.element() method, but the moment I use browser.elements(), I cannot access the individual objects in the array. According to the WebDriverIO docs, I should be able to access them using the value property.
Here is my pseudo-code. I assumed that these two functions should return the same thing:
usingElement() {
return browser.element('.someCss');
}
usingElements() {
return browser.elements('.someCss').value[0];
}
When I try to use the first block of code, it works perfectly fine.. but
when I try to use the second block, it gives me an error saying usingElements.click is not a function or usingElements.getText is not a function, etc.
How can I isolate a single element object after using the browser.elements() method?
I guess you might need to use one of the below two ways:
Way 1:
var elmnts = browser.elements('.someCss');
var element = elmnts.value[0].ELEMENT;
browser.elementIdClick(element);
Way 2:
var element = $$('.someCss')[0];
element.click();
Thanks,
Naveen
Your index reference was placed in the wrong spot. Try:
var myElement = browser.elements('.someCss')[0];
myElement.click();
You don't need to reference the value property, as WebdriverIO is smart enough to infer that for you.
Honestly, I don't know where to start with "extracting." My best guess would be to use the basic .html() tag from JQuery to solve this problem. This is for a small project to improve my JavaScript skills. Any ideas on how this could be done? Thanks so much...
I apologize for being unclear. I meant extracting all the links from a particular page from a domain I don't own. Then, putting these links into an array. Thanks!
Well, this comes to mind ?
var arr = [].slice.call( document.querySelectorAll('a') );
It gets all the matching elements with querySelectorAll, and converts the returned nodeList to an array using [].slice.call, where [] is a shortcut for Array.prototype. In other words it calls the native Array.slice method with call(), passing the elements in as the this value, effectively creating an array from the elements.
if you need the HTML, and not the DOM elements, you can map the elements array and return the outerHTML
var markup = arr.map(function(elem) { return elem.outerHTML; });
or if you just need the URL's, you can run the same map and return the href attribute instead
var urls = arr.map(function(elem) { return elem.getAttribute('href'); });
You don't necessarily need jQuery for this and if learning Javascript is your goal you might be better off without using it for now. querySelectorAll is available in all modern browsers and can accomplish what you are looking for. Per the documentation:
Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.
A NodeList is not an array however so you would need to do a little extra work to make an array of the link elements. You can read in the documentation why they are different.
The selectors used in the method are CSS Selectors and you can checkout the documentation for querySelector for examples.
So to do what you want you could do something like:
var a_list = document.querySelectorAll('a'); // returns NodeList
var a_array = Array.prototype.slice.call(a_list); // converts NodeList to Array
If the jQuery is an acceptable option, you can get all the links by a simple
var links = $('a[href]');
The "links" is an array already.
I would also fiddle around with something like this.
Array.prototype.slice.call(document.querySelectorAll('a'));
Googling it would be a good start so you can learn more about how it works and use it to your advantage.
So I am not sure if my title is clear enough. I essentially have a div saved as a Javascript object which looks like this: [div#field_30.checkbox_group]
The field_30 is the ID which I am trying to extract here. doing something like object.id is not working. Does anyone know how to get the ID?
Note: I saved the object like this: var object = $(".workspace .selected"); which grabs the currently selected div inside the object called workspace. Sorry is this is a rookie mistake, I just can't seem to find anything anywhere. Thanks for the help...
var object = $(".workspace .selected"); will return a jQuery wrapped element that has jQuery properties and methods rather than element properties and methods. This means that any of
object[0].id
object.prop("id")
object.attr("id")
should work, but the 1st option should be the best performance-wise. It gets the id property of the the 1st element contained by the jQuery object, which is your div.
Your object is in fact a jQuery object, not a dom object.
To use the dom object use,
object[0].id
Or using, jquery, (Since it is already there)
object.prop('id');
You can use either $jquery_object.attr('id') or $jquery_object.eq(0).id
See this for exemple: http://jsfiddle.net/cquuT/
In this case it looks like object is the result of a jQuery select. To get to the actual DOM object you need to use [0]. Then you can access the id property
object[0].id
I don't see a complete answer here, so I'll provide my own.
If you're using jQuery selector $(), then you'll get jQuery-wrapped collection, not a single element.
(I assume now that you're using jQuery 1.5.2, the same as StackOverflow uses now.)
Universal solution to get ids of all elements returned by selector is:
.map(function(){ return this.id; })
Running $(".post-text").map(function(){ return this.id; }) on current page will return something like: ["", "", "", "", ""]
To get id of the first element returned by selector use:
.attr('id')
Running $("div").attr('id') on current page will return "notify-container".
Since jQuery 1.6 you can also use .prop('id') here.
If you know, that query will return only one element or you just want the first element matching given selector, then use .attr which is obviously a simpler solution.