Get all element attributes using protractor - javascript

According to the documentation, to get a single attribute by name you can use .getAttribute() on a WebElement:
var myElement = element(by.id('myId'));
expect(myElement.getAttribute('myAttr')).toEqual('myValue');
But how can I get all of the attributes that an element has?
There is no information about this use case/functionality in the Protractor API.

You can expand javascript's Element type and add getAttributes() function:
Element.prototype.getAttributes = function() {
return (function (node) {
var attrs = {};
for (var i=0;i<node.length;i++) {
attrs[node.item(i).name] = node.item(i).value;
}
return attrs;
})(this.attributes);
};
demo
then you can test integrity of attributes using the same method you use for one attribute:
var myElement = element(by.id('myId'));
expect(myElement.getAttributes()).toEqual({'attr1': 'value1', 'attr1': 'value1', ... });

If your attributes that you need are prefixed with data you should be able to use the dataset for the element which will shrink your execute script by a bit:
browser.executeScript('return arguments[0].dataset;', elm).then(function (attrs) {
console.log(attrs);
});

Use executeScript() to execute a script that forms a list of attributes reading them from element.attributes (js part inside is taken from here):
var elm = element(by.id('runButton')).getWebElement();
browser.executeScript(
'var items = {}; \
for (index = 0; index < arguments[0].attributes.length; ++index) { \
items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value \
}; \
return items;', elm).then(function (attrs) {
console.log(attrs);
});
Here attrs would contain a dictionary/object of element attributes with keys as attribute names and values as attribute values.
Demo (using angularjs.org tutorial page, getting all attributes for a header):
$ node node_modules/protractor/bin/elementexplorer.js https://docs.angularjs.org/tutorial
Getting page at: https://docs.angularjs.org/tutorial
> var elm = element(by.tagName('header')).getWebElement();
> browser.executeScript('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', elm).then(function (attrs) {
... console.log(attrs);
... });
{ class: 'header header-fixed', 'scroll-y-offset-element': '' }
Not really beautiful and compact, but works for me. Would be happy to see better alternatives.
UPDATE (an improvement to the approach above):
It would also work if I would define a regular function and pass it in:
function getAllAttributes (arguments) {
var items = {};
for (index = 0; index < arguments[0].attributes.length; ++index) {
items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value;
}
return items;
}
browser.executeScript(getAllAttributes, elm).then(function (attrs) {
console.log(attrs);
});

You have to use browser.executeScript() function call instead of protractor API since Element.attributes is out of protractor API implementation:
var elem = element(by.id('runButton'));
browser.executeScript("return arguments[0].attributes", elem.getWebElement())
.then(function (attrs) {
console.log(attrs.length); // outputs numbers of attributes.
// access collection of Attr objects
console.log(attrs[0].isId); // outputs `true`
console.log(attrs[0].name); // outputs `id`
console.log(attrs[0].value); // outputs `runButton`
});
Remember that when saying attributes, it means a named map structure instead an array in the context of DOM model. Which means you have to use the NamedNodeMap to access collection of Attr objects.
It works as the same way as that in #alecxe's answer without the iteration part.

Related

Get class attribute list [duplicate]

I know you can SET multiple css properties like so:
$('#element').css({property: value, property: value});
But how do I GET multiple properties with CSS?
Is there any solution at all?
jquery's css method (as of 1.9) says you can pass an array of property strings and it will return an object with key/value pairs.
eg:
$( elem ).css([ 'property1', 'property2', 'property3' ]);
http://api.jquery.com/css/
Easiest way? Drop the jQuery.
var e = document.getElementById('element');
var css = e.currentStyle || getComputedStyle(e);
// now access things like css.color, css.backgroundImage, etc.
You can create your own jQuery function to do this:
​
//create a jQuery function named `cssGet`
$.fn.cssGet = function (propertyArray) {
//create an output variable and limit this function to finding info for only the first element passed into the function
var output = {},
self = this.eq(0);
//iterate through the properties passed into the function and add them to the output variable
for (var i = 0, len = propertyArray.length; i < len; i++) {
output[propertyArray[i]] = this.css(propertyArray[i]);
}
return output;
};
Here is a demo: http://jsfiddle.net/6qfQx/1/ (check your console log to see the output)
This function requires an array to be passed in containing the CSS properties to look-up. Usage for this would be something like:
var elementProperties = $('#my-element').cssGet(['color', 'paddingTop', 'paddingLeft']);
console.log(elementProperties.color);//this will output the `color` CSS property for the selected element

Add values from one array to object with specified key & index

Im using the following code,
jQuery.each(aDataSel, function(index, oData) {
oPushedObject = {};
aSelectedDataSet.push(fnCreateEnt(aProp, oData, oPushedObject));
});
This is aSelectedDataSet values
and this is the values of OData
What I need is that before I do the push is to fill the listTypeGroup & listTypeGroupDescription (with the red arrow ) with values that Are inside the oData -> ListTypeGroupAssigment -> result (listTypeGroup & listTypeGroupDescription) , The index is relevant since I want to add just the value of the index in each iteration (since this code is called inside outer loop and the index determine the current step of the loop) ,How it can be done nicely?
The result contain 100 entries (always) and the a selected data will have 100 entries at the end...
Update :)
Just to be clear In the pic I show the values which is hardcoded for this run but the values can be any values, we just need to find the match between the both objects values...
I mean to find a match between to_ListTypeGroupAssigment in both object (which in this case exist ) and if in oData there is result bigger then one entry start with the matching ...
UPDATE2 - when I try Dave code the following happen for each entry,
This happen in the Jquery.extend line...any idea how to overcome this?
The following hard-coded of Dave:-) work perfect but I need generic code which doesnt refer to specific field name
jQuery.each(aDataSet, function(index, oData) {
oPushedObject = {};
fnCreatePushedEntry(aProperties, oData, oPushedObject);
var result = oData.to_ListTypeGroupAssignment.results[index];
oPushedObject.to_ListTypeGroupAssignment = {
ListTypeGroup: result.ListTypeGroup,
ListTypeGroupDescription: result.ListTypeGroupDescription
};
aSelectedDataSet.push(oPushedObject);
});
Im stuck :(any idea how to proceed here ?what can be wrong with the extend ?
should I use something else ? Im new to jQuery...:)
I think that this happen(in Dave answer) because the oData[key] is contain the results and not the specified key (the keyValue = to_ListTypeGroupAssignment ) which is correct but we need the value inside the object result per index...
var needValuesForMatch = {
ListTypeGroup: 'undefined',
ListTypeGroupDescription: 'undefined',
}
//Just to show that oPushedObject can contain additional values just for simulation
var temp = {
test: 1
};
//------------------This object to_ListTypeGroupAssigment should be filled (in generic way :) ------
var oPushedObject = {
temp: temp,
to_ListTypeGroupAssignment: needValuesForMatch
};
oPushedObject is one instance in aSelectedDataSet
and after the matching I need to do the follwing:
aSelectedDataSet.push(oPushedObject);
Is this what you're after:
OPTION ONE - DEEP CLONE FROM oData TO aSelectedDataSet
aSelectedDataSet.forEach(function(currentObject,index){
for (var childObject in currentObject) {
if (! currentObject.hasOwnProperty(childObject))
continue;
var objectToClone = oData[childObject]['results'][index];
if(objectToClone)
$.extend(true,currentObject[childObject],objectToClone);
}
});
Here is your data in a fiddle with the function applied: https://jsfiddle.net/hyz0s5fe/
OPTION TWO - DEEP CLONE FROM oData ONLY WHERE PROPERTY EXISTS IN aSelectedDataSet
aSelectedDataSet.forEach(function(currentObject,index){
for (var childObject in currentObject) {
if (! currentObject.hasOwnProperty(childObject))
continue;
if(typeof currentObject[childObject] !== 'object')
continue;
for(var grandChildObject in currentObject[childObject]) {
var objectToClone = oData[childObject]['results'][index][grandChildObject];
if(typeof objectToClone === 'object') {
$.extend(true,currentObject[childObject][grandChildObject],objectToClone);
} else {
currentObject[childObject][grandChildObject] = objectToClone;
}
}
}
Fiddle for option 2: https://jsfiddle.net/4rh6tt25/
If I am understanding you correctly this should just be a small change:
jQuery.each(aDataSel, function(index, oData) {
oPushedObject = {};
fnCreateEnt(aProp, oData, oPushObj);
//get all the properties of oData and clone into matching properties of oPushObj
Object.getOwnPropertyNames(oData).forEach(function(key) {
if (oPushObj.hasOwnProperty(key)) {
//oPushObj has a matching property, start creating destination object
oPushObj[key] = {};
var source = oData[key];
var destination = oPushObj[key];
//can safely assume we are copying an object. iterate through source properties
Object.getOwnPropertyNames(source).forEach(function(sourceKey) {
var sourceItem = source[sourceKey];
//handle property differently for arrays
if (Array.isArray(sourceItem)) {
//just copy the array item from the appropriate index
destination[sourceKey] = sourceItem.slice(index, index + 1);
} else {
//use jQuery to make a full clone of sourceItem
destination[sourceKey] = $.extend(true, {}, sourceItem);
}
});
}
});
aSelectedDataSet.push(oPushedObject);
});
It is unclear what exactly your fnCreateEnt() function returns though. I am assuming it is the populated oPushObj but it's not entirely clear from your question.

getAttribute by TagName - JS

My specific situation is that I'm trying to remove/make inactive a link element from the DOM (I have no control over it being generated). The way that I plan to do this is through replacing the 'href' attribute with a nonsense value - the reason I've chosen to do it this way rather than simply using disable = true is so that the function can be reused on other occasions to change other attributes.
The problem I'm having is with .getAttribute where it returns the error "TypeError: elemArr.hasAttribute is not a function".
function removeLink(elem, att, value, replacement) {
var elemArr = document.getElementsByTagName(elem);
for (var i = 0; i < elemArr.length; i++) {
var workingAtt = elemArr.hasAttribute(att);
if (workingAtt.value === filePath) {
elemArr[i].setAttribute(att, replacement);
}
}
}
removeLink("link", "href", "filePath", "#");
Any help with why this error is getting thrown is greatly appreciated.
What's going on in there is that elemArr is an array, and arrays don't have a hasAttribute method. Rewrite your code as
function removeLink(elem, att, value, replacement) {
var elemArr = document.getElementsByTagName(elem);
for (var i = 0; i < elemArr.length; i++) {
//this line here wasn't referring to a specific node but the array
var workingAtt = elemArr[i].hasAttribute(att);
if (workingAtt && elemArr[i].getAttribute(att) === value) {
elemArr[i].setAttribute(att, replacement);
}
}
}
removeLink("link", "href", "filePath", "#");
And it will work.
A more succint approach would be something like this:
function removeLink(elem, att, value, replacement){
var selector = elem + '['+ att +'="'+ value +'"]';
[].forEach.call(document.querySelectorAll(selector), function(node){
node.setAttribute(att, replacement);
});
}
It does basically the same thing, but is quite a bit shorter and more explicit.
.hasAttribute() returns a boolean true or false. Therefore, workingAtt will either equal true or false. Boolean values are not HTMLElements, therefore they do not have value attributes. That's why there's an error.
It looks like you're trying to do something like select elements where there is a href attribute.
If so, you can just filter them:
var myElements = [];
[].filter.call(elemArr, function(el) {
if(el.hasAttribute(att)) {
myElements.push(el);
}
});
// then, do something with myElements
You have several errors in your code:
elemArr.hasAttribute instead of elemArr[i].hasAttribute.
var workingAtt = elemArr.hasAttribute(att); — here, workingAtt will be a boolean value, workingAtt.value is non-existent. You should use elemArr[i].getAttribute(att) and later use workingAtt, NOT workingAtt.value (it will be non-existent again!).
if (workingAtt.value === filePath) you're comparing to filePath while you should most definitely compare to value that you pass in the function.

Get element's index after using filter

I have an array with objects. I want to find a specific object's index. This object has an unique id property' value , and i can find it with a $filter :
var el = $filter('filter')( tabs, { id: id })[0]; // "el" is my unique element
But how can i know what is the index of this element in it's original array? Does $filter can provide me this information?
By now i didn't find an Angular solution, because i can't get much useful info on this page. So i have used Array's indexOf method :
var el_index = tabs.indexOf( el );
http://jsfiddle.net/BhxVV/
To get indexes of all elements with specific id we go the similar way:
$scope.getTabsIndexes = function(id){
var els = $filter('filter')( tabs , { id: id });
var indexes = [];
if(els.length) {
var last_i=0;
while( els.length ){
indexes.push( last_i = tabs.indexOf( els.shift() , last_i ) );
}
}
return indexes;
}
http://jsfiddle.net/BnBCS/1/
But it is too long and i'm sure that i'm reinventing the wheel here...
Try this option:
$scope.search = function(selectedItem) {
$filter('filter')($scope.tabs, function(item) {
if(selectedItem == item.id){
$scope.indexes.push( $scope.tabs.indexOf(item) );
return true;
}
return false;
});
}
I think it a bit short and clear.
See Fiddle
I find this simpler and more readable
index = ar.findIndex(e => e.id == 2);
Not sure why you need the original index, but you can add the original index as a new property to the object itself. E.g: write a filter to add the idx:
angular.module('yourModule', [])
.filter('addId', [function() {
return function(arrObj) {
for (var i = 0; i < arrObj.length; ++i) {
arrObj[i].$$originalIdx = i;
}
return arrObj;
};
}]);
Then you can get this expression in html:
{{ tabs | addIdx | filter:{id: 777} }}
Or in javascript:
$scope.getTabIndex = function(id){
var el = $filter('filter')( addId(tabs) , { id: id })[0];
var el_index = el.$$originalIdx;
return el_index;
};
Somehow I can't get it work on jsfiddle, it seems to have trouble with the dependencies injection..

trouble creating nested dom nodes in javascript

I've a function that takes an object as a parameter, and uses the structure of the object to create nested DOM nodes, but I receive the following error:
http://new.app/:75NOT_FOUND_ERR: DOM Exception 8: An attempt was made to reference a Node in a context where it does not exist.
What I would like my function to do, is, when supplied with a suitable object as a parameter, example:
var nodes = {
tweet: {
children: {
screen_name: {
tag: "h2"
},
text: {
tag: "p"
}
},
tag: "article"
}
};
It would create the following DOM nodes:
<article>
<h2></h2>
<p></p>
</article>
Here is my attempt so far:
function create(obj) {
for(i in obj){
var tmp = document.createElement(obj[i].tag);
if(obj[i].children) {
tmp.appendChild(create(obj[i].children)); /* error */
};
document.getElementById("tweets").appendChild(tmp);
};
};
I'm already struggling!
Ideally I'd like to eventually add more child key's to each object, not just tag, but also id, innerHTML, class etc.
Any hel would be much appreciated, though please: I'm sure a framework or library could do this for me in just a few lines of code, or something similar, but I'd prefer not to use one for this particular project.
If you could briefly explain your answers too it'd really help me learn how this all works, and where I went wrong!
Thank you!
NB: I've changed and marked the line in my function that the error message is talking about.
I changed it from:
mp.appendChild(obj[i].children);
to:
mp.appendChild(create(obj[i].children));
This is because I want any nested keys in the children object to also be created, so screen_name had a children key, they too would be created. Sorry, I hope you can understand this!
I'm looking at http://jsperf.com/create-nested-dom-structure for some pointers, this may help you too!
Your "create" function is going to have to be written recursively.
To create a node from your data (in general), you need to:
Find the "tag" property and create a new element
Give the element the "id" value of the element (taken from the data)
For each element in "children", make a node and append it
Thus:
function create(elementDescription) {
var nodes = [];
for (var n in elementDescription) {
if (!elementDescription.hasOwnProperty(n)) continue;
var elem = elementDescription[n];
var node = document.createElement(elem.tag);
node.id = n; // optional step
var cnodes = create(elem.children);
for (var c = 0; c < cnodes.length; ++c)
node.appendChild(cnodes[c]);
nodes.push(node);
}
return nodes;
}
That will return an array of document elements created from the original "specification" object. Thus from your example, you'd call:
var createdNodes = create(nodes);
and "createdNodes" would be an array of one element, an <article> tag with id "tweets". That element would have two children, an <h2> tag with id "screen_name" and a <p> tag with id "text". (Now that I think of it, you might want to skip the "id" assignment unless the node description has an explicit "id" entry, or something.)
Thus if you have a <div> in your page called "tweets" (to use your example, though if so you'd definitely want to cut out the "id" setting part of my function), you'd add the results like this:
var createdNodes = create(nodes), tweets = document.getElementById('tweets');
for (var eindex = 0; eindex < createdNodes.length; ++eindex)
tweets.appendChild(createdNodes[eindex]);
I added a function appendList that accepts a list of elements, and the container to append to. I removed the append to "tweets" part out of the create function to more effectively separate your code.
function create(obj) {
var els = [];
for(i in obj){
var tmp = document.createElement(obj[i].tag);
var children;
if(children = obj[i].children) {
var childEls = create(children);
appendList(childEls, tmp);
}
els.push(tmp);
};
return els;
};
function appendList(list, container){
for(var i = 0, el; el = list[i]; i++){
container.appendChild(el);
}
};
// gets an array of root elements populated with children
var els = create(nodes);
// appends the array to "tweets"
appendList(els, document.getElementById("tweets"));
Building on the previous answer:
I think you still need to create the element you're trying to append:
tmp.appendChild(children[prop].tag);
should be
tmp.appendChild(document.createElement(children[prop].tag));
function create(obj) {
for(i in obj){
var tmp = document.createElement(obj[i].tag);
var children;
if(children = obj[i].children) {
for(var prop in children)
tmp.appendChild(document.createElement(children[prop].tag));
}
document.getElementById("tweets").appendChild(tmp);
};
};

Categories