You can easily retrieve the tag name of an element using the nodeName, like this:
var atnode = document.getElementById("link-test");
alert(atnode.nodeName);
link
But how do I use the nodeName to get the attribute of the element instead?
Using the getAttribute() does not do what I want, because you have to insert the name of the attribute first, and then it just gives you back the value of the attribute. I want to get the name of the attribute just like I did with nodeName. I know nodeName can be used with attribute nodes too, but how?
const atnode = document.getElementById("link-test");
const nodes=[];
const values=[];
for (let att, i = 0, atts = atnode.attributes, n = atts.length; i < n; i++){
att = atts[i];
nodes.push(att.nodeName);
values.push(att.nodeValue);
console.log(att.nodeName + " - " + att.nodeValue);
}
link
After using attributes method you can use nodeName to get the attribute name and nodeValue to get the value of the attribute.
After pushing it to array you can get attribute and value of it using same index in both arrays.
You can get a list of the attributes with getAttributeNames() on the node. In your example, you could do like so:
atnode.getAttributeNames() This will return ["href", "id"].
Then you can loop through the list with getAttribute(<item from list as string>) to get the values of the element's attributes.
If I understood right, you just need to use the getAttributeNames method.
Follows an example:
const exampleElement = document.getElementsByTagName("example")[0];
console.log(exampleElement.getAttributeNames());
<example name="one" last="two"></example>
Related
I need a value of text box for that I am using document.getElementsByName("elemntName") but the problem is the the name itself is dynamic, something like below.
for(temp = 0 ; temp < arracid.length ; temp++){
cell1=mynewrow.insertCell(4);
cell1.innerHTML="<input type='hidden' name='ACID"+index+"' class='tblrows' id='ACID"+index+"' value='"+arracid[temp]+"'>";
index++;
}
When I tried var acidCount = document.getElementsByName('ACID') its not working and I tried
var acidCount = document.getElementsByName('ACID"+index+"') still not working
For every loop the name is changing like ACID1,ACID2 etc.. can anyone help me how to get the value of this text box?
Since you are already assigning an ID to your inputs, it's recommended to use getElementsById which is faster than getElementsByName (and more accurate because the IDs are supposed to be unique, while the names don't have to be). Try this:
var acidCount = document.getElementById("ACID" + index);
If you still want to use getElementsByName, try this:
var acidCount = document.getElementsByName("ACID" + index);
But remember that getElementsByName returns a list of elements, but the list has only one element, because your names are unique. If you want to get that element in the list, you can use it's index like this:
var acidCount = document.getElementsByName("ACID" + index)[0];
Alternatively, if you want to get the list of all your inputs, first remove the index from the name:
cell1.innerHTML="<input type='hidden' name='ACID' class='tblrows' id='ACID"+index+"' value='"+arracid[temp]+"'>";
Then use:
var acidCount = document.getElementsByName("ACID");
Note: all the above return the DOM element(s). If you're only interested in the value, use the value property:
var acidCount = document.getElementById("ACID" + index).value;
or
var acidCount = document.getElementsByName("ACID" + index)[0].value;
(This is a jquery solution, since the question was initially tagged with jQuery)
You can use the selector of input elements with name starting with ^= ACID:
$("input[name^=ACID]").each(function(){
console.log($(this).val());
});
Issue is with single quoutes and double quotes :
var acidCount = document.getElementsByName("ACID"+index)
Since there can be more than one element with same name, so we need to get first element with that name, I have corrected your query check this, it will work.
var acidCount = document.getElementsByName('ACID'+index)[0].value
Try using wildcard * in the selector which will return all matched elements
document.querySelectorAll('[id*=ACID]')
You can try using class name.
$(document).find(".tblrows").each(function(){
console.log($(this).val());
});
Since you are naming your elements 'ACID' + index, you can utilize the querySelector method as follows:
for (var i=0; i < arracid.length; i++) {
var $el = document.querySelector('#ACID' + i));
}
I am using querySelectorAll property initially to obtain nodelists of certain tags,and then from this nodelist i am iterating through each node looking for a certain match to an id property using querySelector,however the result always is null.
var x=document.body.querySelectorAll("script");
for(var i=0;i<x.length;++i)
{
var y=x[i].querySelector("#myid");
console.log(y);
if(y!== null)
{
console.log(i+1);
}
}
i always get an output of null,please help.
If you want to select for example script tags that have the name attribute equal to myName use this:
var elems = document.querySelectorAll('script[name = "myName"]');
You can put as many CSS selectors as ou want to narrow the search.
If you want for example to select div elements that are direct children of li element, and that have the attribute name begin with "abc" and that have an id and a class someClass then use this:
var elems = document.querySelectorAll('li > div[name ^= "abc"][id].someClass');
Here is link to all CSS Selectors!
Krishna your querySelectorAll will grab a nodelist for you. There is no reason for you to add an additional query selector within your loop.
var myId = document.querySelector('#myid');
var collection = document.body.querySelectorAll("script");
for (var i = 0; i < collection.length; i++) {
if (collection[i].includes(myId)) {
console.log(i+1);
}
}
I have an input tag that is being included by a javascript. The resulting input tag looks like this:
<input class="mylivechat_prechat_name_box mylivechat_prechat_box" type="text">
Is there any way that I can add a variable to the end of the value of the input tag?
I've tried using the javascript to set the form field:
var myClassName = document.getElementsByClassName('mylivechat_prechat_name_box mylivechat_prechat_box');
i = myClassName.length;
myClassName[i].value = "TheseAreMyChanges";
However, I get the error
Uncaught TypeError: Cannot set property 'value' of undefined
Array's are zero based, so if you read the length and use that index it is one more than the highest element. Trying to read an element outside the bounds of the array will return undefined - so use length-1:
var myClassName = document.getElementsByClassName('mylivechat_prechat_name_box mylivechat_prechat_box');
var i = myClassName.length;
myClassName[i-1].value = "TheseAreMyChanges";
In your code myClassName[i] will be undefined, since i holds the length and maximum index value will be length - 1. And string can be append at the end by += which results concatenated value.
var myClassName = document.getElementsByClassName('mylivechat_prechat_name_box mylivechat_prechat_box');
myClassName[0].value += "TheseAreMyChanges";
If you want to update the last element then get element by index length -1
var myClassName = document.getElementsByClassName('mylivechat_prechat_name_box mylivechat_prechat_box');
myClassName[myClassName.length - 1].value += "TheseAreMyChanges";
You could use querySelector :
document.querySelector('.mylivechat_prechat_name_box.mylivechat_prechat_box').value+='NEW';
Add :last-child in the end of the selector if you want to get the last element :
document.querySelector('.mylivechat_prechat_name_box.mylivechat_prechat_box:last-child');
Hope this helps.
var elem = document.querySelector('.mylivechat_prechat_name_box.mylivechat_prechat_box');
elem.value += ' NEW';
<input class="mylivechat_prechat_name_box mylivechat_prechat_box" type="text" value='OLD'/>
I am trying to execute a javascript using python selenium. I am basically trying to set the value using execute.script but somehow is it not doing anything. I want to edit the street address as you see below
execute_script(driver, """var element = document.getElementsByClassName('input[ng-model="formData.address.address1"]'); element.value = '328 91st Street'; """)
Could anyone tell me what's the issue here? I am not getting an error also
There is a more robust way of doing it - locating the element with selenium using a CSS selector and passing the WebElement as well as a value into the script as an argument:
elm = driver.find_element_by_css_selector('input[ng-model="formData.address.address1"]')
value = '328 91st Street'
driver.execute_script("arguments[0].value = 'arguments[1]';", elm, value)
Note that in your code, you have 2 major problems:
you are passing a CSS selector into the getElementsByClassName() call - instead, it expects you to pass a class name as a string
getElementsByClassName() returns an array of elements and not a single element
This code is almost good to go...
execute_script(driver, """var element = document.getElementsByClassName('input[ng-model="formData.address.address1"]'); element.value = '328 91st Street'; """)
Just remember that getElementsByClassName will return an array...
And I guess you should use querySelector or querySelectorAll function...
// will select just one element
var element = document.querySelector('input[ng-model="formData.address.address1"]');
// will select all elements
var element = document.querySelectorAll('input[ng-model="formData.address.address1"]');
getElementsByClassName you should inform a class... (I think it's hard to have a class like: ng-model="formData.address.address1")
Using querySelector
var element = document.querySelector('input[ng-model="formData.address.address1"]');
element.value = '328 91st Street';//Work!!!
In case you want to iterate in these NodeLists with querySelectorAll
Basically,
var element = document.querySelectorAll('input[ng-model="formData.address.address1"]');
element.value = '328 91st Street';//WON'T WORK
Do instead:
var element = document.querySelectorAll('input[ng-model="formData.address.address1"]');
element[0].value = '328 91st Street'; // change the value for the first element
for(int i = 0 ;i<element.length;i++){ //change all elements
element[i].value = '328 91st Street';
}
I have an attribute for a set of HTML5 objects that is an array. Something like
<button attr=[1,0,0,0,1,1]>test</button>
<button attr=[1,1,0,0,1,1]>test</button>
...
How do I formulate a jQuery selector to match only elements whose n-th value of attr is 1? Something like $("attr[1]=1") that would only select the second button from this example (this syntax does not work, but I wrote it just to give an idea of what I need).
In my case I am not dealing with buttons but with other types of objects, I just wanted so simplify the context of the question.
You can use a custom filter to select only the matched elements.
<button data-attr="[1,0,0,0,1,1]">button 1</button>
<button data-attr="[1,1,0,0,1,1]">button 2</button>
Note that attr is not a valid html attribute for button. I'd suggest you use the data-attr instead. You can use .data('attr') to get the data back.
var selected = $('button').filter(function (idx) {
var attr = $(this).data('attr');
return attr && attr[1] == 1;
});
alert(selected.html());
jsFiddle Demo
You can write your own selector like this (i called it "array", you can use a better name here):
jQuery.expr[':'].array = function (elem, index, match) {
var params = match[3].replace(/^\s+|\s+$/g, '').split(/\s*,\s*/),
attribute = params[0],
arrayindex = parseInt(params[1]),
matchvalue = params[2],
value = JSON.parse($(elem)[attribute](attribute));
return value[arrayindex] == matchvalue;
};
Then, use it like any other selector where the first parameter is the name of the attribute, the second parameter is the index in your array and the third parameter is the expected value:
$('button:array(attr,1,1)');
Fiddle: http://jsfiddle.net/pascalockert/uDnK8/2/