Retrieve a particular path element by its assigned ID

I am currently using Topojson along with world-110m.json to create a visual map of the world. My goal is to be able to change the fill property of two specific countries upon a click event.

The first country will be selected by the user through a click, and the ID of that particular path will be obtained using:

var current_country = d3.select(this).style("fill", "red");
var current_country_ID = d3.select(this).attr('id');

The second country to modify is predetermined (not important), and it is identified by its unique ID. I attempted to alter its fill color using:

var top = d3.select("path#643").style("fill", "green");

Referencing this suggestion provided here: How to select a d3 svg path with a particular ID

Even though this process seemed straightforward, I consistently encounter the same error message regardless of what I do:

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': 'path#643' is not a valid selector.

I have experimented with various approaches and reviewed similar queries posted here, but unfortunately, I have been unable to identify the correct solution. The path with the specified ID does exist. Additionally, all the countries are stored in the 'world' variable, which appears to be accurate based on my examination.

Below you can see the complete code snippet:

    var width = 2000;
    var height = 2000;

    var svg = d3.select("body").append("svg")
              .attr("width", width) 
              .attr("height", height);

    var projection = d3.geo.mercator()
              .center([50,70]) 
              .scale(150) 
              .rotate([0,0,0]); 

    var path = d3.geo.path().projection(projection); 

    var g = svg.append("g"); 

    var country_selector = d3.select("body").append("div").attr("class", "country_selector"); 

    queue() 
      .defer(d3.json, "world-110m.json")
      .defer(d3.csv, "country_data2.csv")
      .await(main);

    function main(error, world, countryData){

        var country_names = {}; 
        var countries = topojson.feature(world, world.objects.countries).features;

        countryData.forEach(function(d) {
        country_names[d.id] = d.name; 
        });

        var world =  g.selectAll("path") 
                    .data(countries)
                    .enter()
                    .append("svg:path")
                    .attr("d", path)
                    .attr("id", function(d) { return d.id; })
                    .attr("class", function(d) { return d.id; })
                    .on("mouseover", function(d) {
                    country_selector.text(country_names[d.id])
                    .style("left", (d3.event.pageX + 7) + "px")
                    .style("top", (d3.event.pageY - 15) + "px")
                    .style("display", "block")
                    .style("opacity", 0.8);
                    })
                    .on("mouseout", function(d) {
                    country_selector.style("opacity", 0)
                    .style("display", "none");
                    })
                    .on("mousemove", function(d) {
                    country_selector.style("left", (d3.event.pageX + 7) + "px")
                    .style("top", (d3.event.pageY - 15) + "px");
                    })
                    .on("click", function(d) { // the challenging part
                    var current_country = d3.select(this).style("fill", "red")
                    var current_country_ID = d3.select(this).attr('id')
                    console.log(current_country)
                    console.log(current_country_ID)
                    console.log(world)
                    var top = d3.select("path#643").style("fill", "green"); // causing trouble
                    console.log(top)
                    })  
    }; // end of main function

    var zooming = d3.behavior.zoom() 
                .on("zoom",function() {  
                    g.attr("transform","translate("+ 
                        d3.event.translate.join(",")+")scale("+d3.event.scale+")");
                    g.selectAll("path")  
                        .attr("d", path.projection(projection)); 
                });

    svg.call(zooming).on("dblclick.zoom", null);

Your assistance would be immensely appreciated.

Answer №1

IDs cannot begin with numbers, making the ID itself invalid. To resolve this issue, you can modify the ID in the HTML to something like _643, and then in your JavaScript code, use:

var top = d3.select("path#_643").style("fill", "green");

Here's an illustration demonstrating CSS usage for ID validity

#643 {
background-color: orange;
color: #FFF;
}
#_643 {
background-color: orange;
color: #FFF;
}
#-643 {
background-color: orange;
color: #FFF;
}
#six43 {
background-color: orange;
color: #FFF;
}
<ul>
<li id="643">643</li>
<li id="_643">_643</li>
<li id="-643">-643</li>
<li id="six43">six43</li>
</ul>

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

Having trouble passing data from JavaScript to PHP with AJAX

I attempted to use AJAX to send data from an array (emp) and other string variables like 'gtotal' in my code, but the data did not transfer to the PHP file. Despite no errors being shown, when I removed the isset() function it displayed an error ...

What is the best way to display multiple files in a vertical stack when choosing a file?

<div class="selected-file-container align-items-center justify-content-between d-none"> <div class="selected-file d-flex align-items-center"> <img id="selectedImage" class="hidden" src="&qu ...

Transformation in CSS3 is not supported for DIV elements

Seeking help to implement a "Flip card" effect on div elements (cards). I have applied the code below, but encountering an issue. The goal is to flip the "Card" Div element by utilizing the JavaScript function "OpenCard()" provided below. EDIT 1: Added js ...

IE8 does not support Jquery ajax() for cross domain requests to remote servers

My current script includes an ajax request to a remote server that provides a plain text response. This setup functions properly in all browsers with the exception of IE8, which is not surprising. The script snippet looks like this: $.ajax({ url: &apos ...

Unique validation feature implemented in Parsley.js runs through validation loop twice

I've spent the entire afternoon trying to figure this out, but I just can't seem to debug it. The issue arises when I do a hard refresh of the page and my custom async validator runs twice, yet only sends one request to the server. window.Parsle ...

Angular is unable to successfully send a post request to Node

Whenever I click on the submit button on the frontend, it triggers the upload() function. This is how it is implemented in my app.html: <div class="row" style="padding:10px;"> <button type="submit" class="btn btn-primary" style="margin ...

What is the best way to prevent certain search terms from appearing in search results on my website's search form

Is there a way to prevent certain search terms from showing up in my search box? For example, how can I block the search query for "dog"? <form id="headbar-search" action="search.php" method="GET" x-webkit-speech="x-webkit-speech"> <input type="t ...

Unable to establish connection with remote database server on Hostinger platform

I've been encountering this persistent error that I can't seem to resolve. I developed my project locally, utilizing a local database. Upon completion, I attempted to manually migrate my database to my hosting provider since it's relatively ...

React JS Issue: Real-time Clock not updating in React component

I have a react application designed for attendance tracking. The issue at hand is that the time displayed does not update in real-time. Once the app is initially rendered, the time remains static. (It only updates when the app is reloaded) The code snipp ...

What is the process for implementing form validation in JavaScript?

I am currently learning JavaScript and trying to incorporate a form validation feature in my main.handlebars file. Below is the code snippet from my main.handlebars: <form method="post" action="/save" onsubmit="return validateform()" name="myForm"> ...

links to css and javascript

I am having trouble with what should be a simple task! On my webpage, I have this link: <a class='action' href='javascript:void(0)' OnClick='run()'> run </a> Along with the following CSS: .action { color: # ...

What is the most effective method for importing icons in React?

What is the most efficient method for importing icons? Solution 1: Utilizing a react svg library such as react-icons Often, these libraries export all icons in a single file index.ts, resulting in loading thousands of unnecessary icons during development ...

Using expect() within the .then() function when writing Jasmine unit tests for AngularJS

I'm currently struggling with the .then() function while trying to implement Jasmine unit testing. Here is the code that's giving me trouble: describe("getBuilding", function () { it("checks getBuilding", function () { var id_building = 4; ...

Unusual scroll bar movements when using jQuery validation

When I click the Add Dependent link button, I wanted the scroll bar to automatically scroll to the bottom, and it does just that. However, there is a small issue after the postback where the text "Please fix the following problems:" briefly appears, even t ...

Error: Module not located or Image unable to load in React JS

Here is the structure of my project : src -assets fut.png -components -admin_dashboard Sidebar.js -App.js -pages Dashboard.js I encountered an issue trying to load the image fut.png from the file Sidebar.js. Even after attempting ...

Unresponsive Three.js OrbitControls

*Update: I'm feeling a bit confused because I don't believe my function is causing this issue. It seems that simply double-clicking without moving the mouse triggers this behavior consistently, even in the Three.js example. I'm still unsure ...

merging pictures using angular 4

Is there a way in Angular to merge two images together, like combining images 1 and 2 to create image 3 as shown in this demonstration? View the demo image ...

The function of window.location is a mixed bag of success and failure

I am encountering an issue with a JavaScript function that is supposed to navigate to the next page when clicking a button. The function works correctly for step 1, but it fails for step 2. Upon executing the function using nextstep = 'form', _b ...

What causes the strings in an array to be split into individual characters when using the jquery each() function?

After successfully loading jquery, I have initialized an array (object) with various strings: window.stack = [ "header", "nav", ".content", "footer" ]; My intention was to loop through this array using jquery's each() function to retrieve ea ...

Developing a web-based form using an ES6 module

I'm currently experimenting with an ES6 webpage to design a simple webpage featuring just an email form. The form includes fields for Name, Email, and Subject, a message text box, and a send button that is linked to a PHP script to deliver the email ( ...