Get raw element from d3 selection - javascript

I'm building a custom visual for Power BI, written in TypeScript. In my class' constructor I write this.svg = d3.select(this.target).append("svg").attr("id", "svg"); (this.target just holds a standard HTML element, it's not important for the question).
My question is ,using this.svg, how can I obtain just the raw SVG element? From Googling it seems I should be able to use this.svg.node(), but there must be something subtle going on that makes this different to the "true" element...
When I run console.log(this.svg.node()), its output appears exactly the same as console.log(document.getElementById("svg")) in Chrome's developer window, so that's fine.
However, using the expression this.svg.node().getBoundingClientRect() causes my TypeScript to not compile because of the error Property 'getBoundingClientRect' does not exist on type 'Node', whereas document.getElementById("svg").getBoundingClientRect() returns the correct value.
How do I just get the true, raw DOM element that this.svg refers to?
I'm using d3 v3.

.node() is returning the real element, the problem here is that in other situations .node() can return other types of objects than just Elements, so the typescript compiler can't know it'll definitely have the getBoundingClientRect() function.
The solution is to cast the object as type Element:
var svgElement = this.svg.node() as Element;
var boundingRect = svgElement.getBoundingClientRect();

Related

How to get all possible valid attributes on a DOM element [duplicate]

This question already has answers here:
How to list all element attributes in JS?
(3 answers)
Closed 5 years ago.
Please note that .attributes only gets the current attributes, which is not what this question is about.
I want a way to get all the attributes of a DOM element. Not just the ones that are on it now, but the ones that are possible in the future too.
The specific use case is to find the potential attributes in an SVGElement that aren't in an HTMLElement - there's a list on MDN (SVG Attribute reference), but, for obvious reasons, hardcoding is not a good idea.
My initial thought was to iterate through the prototype chain of an instance of each and compare the two lists (with basic filtering for event handlers), but this doesn't actually give the potential svg attributes.
EDIT
IMPORTANT NOTE - pasting your answer code into the console on this page and using document.body as a target should show a list of over 50 attributes, including things like contentEditable, contextMenu, dir, style, etc.
This also needs to work cross-browser.
Could something like this be what you're looking for?
It looks like a DOM element object stores empty keys for all possible attributes. Could you loop over these keys and store them in an array, then from there use something similar to filter out inherited attributes?
HTML
<svg id="blah"></svg>
Javascript
const blah = document.getElementById('blah')
let possibleKeys = []
for (let key in blah) {
possibleKeys.push(key)
}
Here's a JSBin example ... it looks like it produces a list of all possible attributes but it would need some filtering.
See also this thread.
How to list all element attributes in JS?
Any one of these should work because they return a live HTMLCollection.
var svgElement = window.document.getElementsByClassName("someSvgClass")[0];
//assume someSvgClass is on svg element.
//var svgElement = window.document.getElementsByTagName("svg")[0];
//var svgElement = window.document.getElementsByName("mySvg")[0];
//assume svg has this name.
var svgAttributes = svgElement.attributes;
for(let i=0; i<svgAttributes.length; i++) {
console.log(svgAttributes[i]);
}
See the below documentation from MDN on getElementsByTagName()
The Element.getElementsByTagName() method returns a live
HTMLCollection of elements with the given tag name. The subtree
underneath the specified element is searched, excluding the element
itself. The returned list is live, meaning that it updates itself with
the DOM tree automatically. Consequently, there is no need to call
several times Element.getElementsByTagName() with the same element and
arguments.
The documentation for getElementsByName , and getElementsByClassName say the same thing; a live node list is returned. If you'd like to try it, I created a fiddle here.
You'll see that svgAttributes list is automatically updated upon clicking "Add Attribute" without re-executing any of those functions.
There is no API for that and I don't think a workaround is possible because when you change an attribute on a current DOM node, the browser is responsible for re-rendering and updating the webpage in a low-level way that is not exposed to the JavaScript context.
Also, keep in mind that any correctly formatted attribute is actually valid in the context of a DOM tree, even though it might not trigger any change at the rendering level or in the way the browser renders the page. Especially the data-* attributes.
There might be some vendor-specific API but that wouldn't be useful if you want cross-browser compatibility.
You need to hardcode it, sadly. Given that you specifically want the SVGElement attributes, maybe you can scrape the W3's SVG standard document to automatically create the list?
Edit: I made a snippet to easily scrape the values from the standard:
const uniq = arr => Array.from(new Set(arr))
const nameElements = document.querySelectorAll('table[summary="Alphabetic list of attributes"] .attr-name')
const arrNameElements = Array.prototype.slice.call(nameElements)
const svgAttributes = uniq(arrNameElements.map(el => el.innerText.replace(/\‘|\’/g, '')))
Just execute it on the svg attributes page, by opening the dev console on the page and pasting in this code :)
Edit 2: I forgot the presentation attributes. I'll let you figure that one out ;)

How to develop a custom protractor locator?

I have an angular-application where I put custom html-attributes ("data-testid='saveButton'") for identification on e.g. buttons, inputs etc.
Protractor has no built-in locator for this: the xpath-way does not work as this will always search from the document root (to overcome this limitation I would have to do quite a lot of string-magic to build the xpath-string, so I discarded this variant).
So I wanted to write my own locator, and consulted the official Protractor Documentation.
The documentation leaves me with an important question:
What methods are available on the parent-element-object? In their example they use using.querySelectorAll('button'); but how do they know they can use this?
I searched for 'querySelectorAll' in the protractor-documentation to see if it is maybe a method of ElementFinder or WebElement, but I didn't find it.
Also I found no way to debug the locator (only stop the protractor-test by browser.pause()), so I can't look at runtime to see what I can do with the given parent-element.
So does anybody know how I can get information about what methods the parent-element has?
The parent-element, which is essentially the context of the selector is a DOM element that gets handled by the browser - it can use whatever DOM function there is, in this case Element.querySelectorAll. As the addLocator's example says about the function you pass to it:
This function will be serialized as a string and will execute in the browser.
Also, keep in mind that there is a way to provide context to the xpath selectors thus avoiding the search from root:
var context = element(by.css('.some-parent-element-class'));
var divDirectDescendants = context.element(by.xpath('div'));
var divAllDescendants = context.element(by.xpath('.//div'));
With CSS these would be:
var divDirectDescendants = element(by.css('.some-parent-element-class > div'));
var divAllDescendants = element(by.css('.some-parent-element-class div'));
Also, there's a way to achieve what you want with a CSS selector (which is what querySelectorAll is, after all):
var everyElementWithMyAttr = element.all(by.css('[data-testid="saveButton"]'));

d3 create object without appending

I'm using d3 for graphing, and I'm trying to create an svg object, to add to the DOM later.
I used to have
var svg = d3.select(el).append("svg");
var graph = svg.append("g")
...etc...
and for reasons I won't go into, I wanted to create the svg element before appending it to the DOM.
So I did
var svg = d3.select(document.createElementNS(d3.ns.prefix.svg, 'svg'))
var graph = svg.append("g")
...etc...
, which works, and while debugging, I can see that svg is a 1-element array, with the children nicely attached.
The problem comes at the append step:
d3.select(el).append(svg);
There, I get an error Error: Failed to execute 'createElementNS' on 'Document': The qualified name provided ('[object SVGSVGElement]') contains the invalid name-start character '['. I've taken a look here: How to create "svg" object without appending it? but it seems that's exactly how they suggest it.
Any idea why this is so? I've tried appending svg[0], but no luck either. It seems append() only takes strings as an argument.
edit: the d3 reference at https://github.com/mbostock/d3/wiki/Selections#append states
selection.append(name)
... ... ...
"The name may be specified either as a constant string or as a function that returns the DOM element to append."
Consequently I've tried
d3.select(el).append(function(){return svg;});
but that fails with a Error: Failed to execute 'appendChild' on 'Node': The new child element is null.
If svg is a selection, svg.node() returns the DOM element, e.g.:
d3.select(el).append(function(){return svg.node();});
(Mind you, I'm not certain that svg in your case is a true selection, but you could give it a try.)
You might be better off using the regular element.appendChild function for this.
You can get a reference to your parent element using d3.select(el).node() then, you can call .appendChild on that, passing in svg.node() as the element to append.
So, all together:
d3.select(el).node().appendChild(svg.node());

How to tell the type of a JavaScript and/or jQueryobject

This question pertains as much to the ECMAScript language implementation we know as JavaScript as it does to jQuery and the developer tools availble in most popular browsers.
When you execute a statement like so:
var theElement = $('#theId').closest();
what is the type of theElement?
I assume that in a jQuery situation like above, many jQuery methods including the one above actually return the jQuery object itself, which packages the stuff you actually want to get to. This, so that it may maintain a fluent API and let you join method calls in a single statement like so:
$('#selector').foo().bar().gar().har();
However, in the case of jQuery then, how do you determine what the real underlying type is? For example, if the element returned was a table row with the Id tableRowNumber25, how do you get to that, say, using FireBug.
When I look at either a jQuery returned object or a simple JavaScript object in the watches window of Firebug or any of the Developer Tools in most popular browsers, I see a long laundry list of properties/keys and I don't know which one to look at. In a jQuery object, most of the properties are lamdas.
So, really, my question is -- how do you know the underlying type, how do you know what's actually being returned?
The type of theElement will be [object jQuery].
If you want the HTML element itself, you have to select it:
console.log(theElement[0]) //Return <div id='theId'>
console.log(theElement.get(0)) //Return <div id='theId'>
If you want the node name, there is a property in the HTML node element call nodeName wich return the capitalised node name:
console.log(theElement[0].nodeName)// Return DIV
typeof(jQueryElementList.get(0)) will return a string of the type.
Some browsers might return this as upper or lower case, I think. IE probably uppercases (see Testing the type of a DOM element in JavaScript). Apparently you can check the nodeType attribute (jQueryElementList.get(0).nodeType) to determine whether it is an html object/tag.

Removing Chrome's "translate" DOM Property

I'm working with some legacy code where the original developers made heavy use of generating HTML DOM nodes with a non-standard attribute named translate
<span translate="[{"shown":"My Account","translated":"My Account","original":"My Account","location":"Text","scope":"Mage_Customer"}]">My Account</span>
and then traversing/searching for those nodes with javascript code like the following.
if (!$(target).match('*[translate]')) {
target = target.up('*[translate]');
}
The problem I'm trying to solve is, it appears that Google Chrome automatically adds a translate attribute to every DOM node in the document, and that this DOM node's value is a boolean true. You can see this by running the following Javascript from Chrome's javascript console
> document.getElementsByTagName('p')[0].translate
true
>
Is there anyway to tell Chrome not to populate these attributes? Their presence is wrying havoc with the legacy code. PrototypeJS's match and up nodes treat these boolean object attributes as matches, while the code I'm dealing with is specifically looking for DOM nodes with an attribute named translate. I'd like to find a solution for my problem that doesn't involved rewriting the old Javascript to use methods like hasAttribute.
I tried (as a wild guess) adding the meta attributes mentioned in this article,
<meta name=”google” value=”notranslate”>
<meta name=”google” content=”notranslate”>
but the nodes in the page still has a boolean true translate attribute.
(if it matters, this is Magento's inline translation system I'm talking about here)
The best I've been able to come up with so far is going through every DOM element in the page defining a getter that checks for the existence of an attribute. (the Object.__defineGetter__ guard clause ensures no errors in browsers that don't support modern Javascript)
if(Object.__defineGetter__)
{
var hasTranslateAttribute = function(){
return $(this).hasAttribute("translate");
};
document.observe("dom:loaded", function() {
$$('*').each(function(theElement){
theElement.__defineGetter__("translate", hasTranslateAttribute);
});
});
}
I tried defining a getting on Object.prototype and Element.prototype, but it seems like the browser's native translate is defined higher up the chain, so you need to redefine things on a per element basis.
Replace the nonstandard attribute translate by an attribute like data-translate, which is virtually guaranteed to be and to remain undefined in HTML specifications and in browsers. The data-* attributes were invented to prevent issues like this, and they can also be used to fix them.

Categories

Resources