I have a Problem with using jQuery together with D3js.
I have a jQuery element named "elem" and I want to do some D3js functions.
This code works:
d3.select("body").append("svg").attr("width", 300).attr("height", 300).append("g").attr("transform", "translate(150,150)").selectAll("text").data(words).enter().append("text")......
This code does not
elem.append("svg").attr("width", 300).attr("height", 300).append("g").attr("transform", "translate(150,150)").selectAll("text").data(words).enter().append("text")......
So how to convert the jQuery Object into a D3 Object?
d3 does not directly use jQuery, so the jQuery library of functions is not directly accessible in d3 by default.
The jQuery selector finds particular DOM element(s) and wraps them with jQuery object. For example, document. getElementById() in the JavaScript will return DOM object whereas $('#id') will return jQuery object.
The Document Object Model (DOM) elements are something like a DIV, HTML, BODY element on the HTML page. A jQuery Selector is used to select one or more HTML elements using jQuery. Mostly we use Selectors for accessing the DOM elements.
A jQuery object is array-like which means that it contains zero or more indexes (properties which names are positive integers starting with zero). Besides those indexes, a jQuery object contains these properties: length. context. selector.
You can get the DOM Elements themselves from the jQuery object using .get() method or array notation on the jquery object, and then select them with d3 selector like you would any DOM Element.
Note that while both works, jQuery faq mentions that array notation is faster.
d3.select($("#selection").get(0));
d3.select($("#selection")[0]); // equivalent to above but faster
Edit: Thanks to Ken Fox for pointing out jQuery faq.
You can't convert the objects directly. You need to re-select the element using d3js
. d3js
selectors work like this
d3.select("#mydiv")
So simply extract the id
from the jQuery
element like so
d3.select("#" + elem.attr("id")).append("svg").attr("width", 300)...
Of course if you're only using jQuery
to select the element, then you should switch to d3js
selection instead.
EDIT: I prefer Ozan's answer above, use that!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With