How to retrieve HTML attribute using D3 techniques

Looking to iterate through all rect nodes in the code snippet below:

d3.selectAll("svg g rect")
    .on('mouseover', function (d) {
        console.log(this);
}); 

When Console.log is executed, the following is printed:

<rect class="cls" name="UK" style="fill: #fdb462;" transform="translate(52 50)" x="805.625" y="0" width="13.75" height="229.018" >...</rect>

To access the value of the "name" attribute (which is "UK") of the rect tag, attempting this.name has not been successful. How can this be achieved?

Answer №1

To efficiently retrieve the value of name in D3, one can utilize selection.attr() as a reliable getter:

d3.select(this).attr("name")

Check out this demonstration:

d3.select("rect")
  .on('mouseover', function(d) {
    console.log(d3.select(this).attr("name"));
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
  <rect class="cls" name="UK" style="fill: #fdb462;" transform="translate(52 50)" x="0" y="0" width="200" height="100"></rect>
</svg>

Essentially, selection.attr() internally employs getAttribute (or getAttributeNS). Hence, it is synonymous with:

this.getAttribute("name")

Explore this example to understand its functionality better:

d3.select("rect")
  .on('mouseover', function(d) {
    console.log(this.getAttribute("name"));
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
  <rect class="cls" name="UK" style="fill: #fdb462;" transform="translate(52 50)" x="0" y="0" width="200" height="100"></rect>
</svg>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to retrieve all the text inside an element using Protractor and Selenium

<div class="test"> <span> <div>CONTENT </div> </span> <div> <ul> <li> <span>More text</span> EXAMPLE1</li> <li>EXAMPLE2</li> ...

AngularJS allows for versatile filtering of objects and arrays using checkboxes

I am looking to implement a filter functionality similar to the fiddle mentioned in the first comment below. However, I do not want to capture the checkboxes category from ng-repeat. Instead, I only want to input the checkboxes' value and receive the ...

The meshes in my Unity game appear flipped after I import them from 3ds Max with skinning applied

After bringing my meshes from 3ds MAX to Unity with skinning, I've noticed that they appear inverted in-game. Both the mesh and normals seem to be reversed, giving them an eerie, ghost-like appearance. Interestingly, disabling the skin option resolv ...

Access the array values by their respective keys in an object that is returned from a custom JavaScript file utilizing the Node.js file system

I recently came across a config file with a unique format, as shown below: define([], function () { return { productItems: { item1: ['Apple', 'Ball', 'Car'], item2: [&apo ...

Can hash routes be defined in next.js?

Previously, I created a modal component using <HashRouter> in react-router where the modal would become active or inactive based on the hash url. For example, the modal is inactive when the url is /route, but becomes active when the url is /route#m ...

How to display a modal within a router-link in Vue 3?

Below are buttons with router-links. However, I only want the calculator button to open a modal. When I execute the code provided, all buttons trigger the modal instead of just the calculator button. Output: Router-link Code: <div class="contai ...

Receiving the most recent data in a protractor examination as a text string

My goal is to fetch an input value for a specific operation in protractor. I am attempting to make an ajax request using protractor and need to assign a unique value (referred to as groupCode) to a JSON object that will be sent to the server. Initially, I ...

Are there options available in nightwatchjs for making intricate decisions with selectors?

When using the NightWatch JavaScript Selenium tool, it is important to establish good practices for identifying different parts of the GUI before running tests. For example, distinguishing between options A and B and creating separate tests accordingly. An ...

Having trouble with JavaScript/JQuery not functioning properly in HTML content loaded using the load() method

My goal is to load an input form from a separate file called new_machine.php into my index.php. This form includes an input with a dropdown that retrieves options from a MySQL database and displays them as anchors. The issue arises when I attempt to manipu ...

Top method for organizing an array based on an object's property and displaying the outcome

I encountered a problem for which I couldn't find an immediate solution. I have an array of objects representing products, with each product having a category property. My goal is to group these products by their categories. After some trial and error ...

"Looking for a way to automatically close the <li> tag in Vuejs when clicked outside

clickOutside: 0, methods: { outside: function(e) { this.clickOutside += 1 // eslint-disable-next-line console.log('clicked outside!') }, directives: { 'click-outside': { ...

You can install the precise version of a package as mentioned in package.json using npm

At this moment, executing the command npm install will download the latest versions of packages. Is there a way to install the exact versions specified in the package.json file? ...

Identify numbers and words within a sentence and store them in an array

Looking to split a string into an array based on type, extracting numbers and floats. The current code is able to extract some values but not complete. var arr = "this is a string 5.86 x10‘9/l 1.90 7.00" .match(/\d+\.\d+|\d+&bsol ...

Manipulate the DOM to remove a checkbox using JavaScript

I'm brand new to exploring the world of Javascript and could use some guidance with this task. I have a collection of checkboxes that I'd like to manipulate so that when one is checked, it disappears from the list automatically. I've come ac ...

What is the best method for saving and retrieving a class object in a web browser's storage?

Looking for a way to create page-reload proof class instances in my Angular 2 application. Within my component's .ts file, I have defined the following classes: export class AComponent implements OnInit { foo: Foo = new Foo(); ngOnInit() { / ...

Modifying array elements in JavaScript without explicit instructions

I am relatively new to Javascript and seem to be encountering a rather puzzling issue that I'm unable to resolve. Currently, I have two classes: Country and PPM_Data. The Country class contains parameters such as name, area, ppm, etc., along with a f ...

Showing scheduled activities from a database on an AngularJS mwl calendar

How can I modify my code to display events from a database on an mwl calendar based on the saved date rather than showing all events for today only? I want to show events based on the notifyDate field in the database. Can someone help me with this? html ...

Encountered an error: Trying to access 'location' property from undefined in express app

Encountered Issue : I am facing an error that is hindering me from fetching data from the HTML form. Every time I input values into the form and click the button to send the data to an API for saving it in the database, this error pops up: Cannot read pro ...

Why is my Cloud Storage Cloud upload file showing a file size of "0 bytes" (Node)?

I am having issues uploading a PDF file to Google Cloud Storage as the file size appears to be 0 bytes. I have been trying to resolve this for the past 3 days but have not received any response. Here is the code snippet that I am using: const cv = req ...

"Utilizing Material-UI in React to create a textfield input with number validation

I am currently working on an input field that should only accept values within a specified range of min and max. However, I have encountered an issue where manually entering a number bypasses this control mechanism. Is there a way to prevent this from happ ...