Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a jQuery object into a d3 object?

Tags:

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?

like image 406
Niko Lang Avatar asked Jan 20 '15 12:01

Niko Lang


People also ask

Does D3 use jQuery?

d3 does not directly use jQuery, so the jQuery library of functions is not directly accessible in d3 by default.

Which methods return the element as a jQuery object?

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.

Is it possible to access the underlying DOM element using jQuery?

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.

What is jQuery object?

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.


2 Answers

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.

like image 82
Ozan Avatar answered Sep 28 '22 22:09

Ozan


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!

like image 29
roryok Avatar answered Sep 28 '22 20:09

roryok