Unable to locate the element with the specified id: <path>

I am aiming to dynamically change the fill attribute of a specific <path> element when a page loads.

Here is the detailed information about the path element:

<path xmlns="http://www.w3.org/2000/svg" 
style="fill:#ff0000;stroke:#000000;stroke-width:0.26458332px;stroke- 
linecap:butt;stroke-linejoin:miter;stroke-opacity:1;fill-opacity:1" 
d="M 71.895501,10.754349 94.88068,-28.80154 112.52047,12.892505 Z"
id="element"/>

This <path> element resides within a map.svg file that I embed in my HTML using an <object> tag, as suggested by a helpful reply on StackOverflow.

index.html

Below is the content of the HTML file:

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Dental Ordination</title>
        <script src="svg.min.js"></script>
        <script src="jquery.min.js"></script>
    </head>
    <body>
        <object type="image/svg+xml" data="map.svg"/>
        <script src="main.js"></script>
    </body>
</html>

main.js

Here is an excerpt from my JavaScript file:

$(document).ready(function () {
    $("#element").attr("fill", "blue");
});

Upon execution, the fill color of the path does not change as expected. To troubleshoot this issue, I included

console.log($("#element").attr("fill"));
in the script to check its return value, which turned out to be undefined.

Answer №1

Why not change this code snippet:

$(document).ready(function () {
    $("#element").attr("fill", "blue");
});

to something like this instead:

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('element').style.fill = 'blue';
})

The reason for this adjustment is that the element does not possess a fill attribute, but rather a fill style.

In regards to your follow-up inquiry, consider:

console.log($("#element").attr("fill"));
. This command returns undefined as there is no attribute called fill. Instead, you can use console.log(element.style.fill).

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

Unable to trigger jQuery onclick event on nested div elements

I'm experiencing an issue with my web-page where two buttons at the top are not responding to a sorting function on the nested #byFilter. Despite trying to apply the onclick(function()) method, it doesn't seem to work. Javascript $(document).re ...

The URL is unresponsive following the deployment of the production build in tailwind

The image URL in my project is functioning correctly in the VITE server environment before the production build. However, after the production build, it fails to display the correct path of the image in the HTML. All other images are displaying properly ex ...

modifying prop values with Vue.js method

I'm currently diving into Vue and tackling a project that heavily relies on vue.js. My goal is to display data in a component using a prop, and now I'm looking to implement a method to increment the quantity of a product. Below is my code snippe ...

Experiencing an issue with Jest - Error: unable to access property 'forEach' of null

After watching some tutorials, I decided to create a sample project in Jest for writing tests. In a TypeScript file, I included a basic calculation function like this: Calc.cs export class Calc { public add(num1: number, num2: number): number { ...

Creating a triangle with SVG polygon: A step-by-step guide

I'm attempting to create a bottom triangle using SVG polygons, similar to the image below: https://i.stack.imgur.com/571FM.png Here is what I have tried so far: <svg xmlns="http://www.w3.org/2000/svg" height="150px" width="100%" viewBox="0 0 ...

NodeJS - Bluebird: implementing a loop with a waiting mechanism for completion

Struggling with a seemingly simple task in my NodeJS and MongoDB project. I've included Bluebird for promises, but need some help. In my code, I have a basic for-loop that generates random names and pushes them into an array: const PlayerGenerator = ...

Using jQuery Ajax to Retrieve Selected Text from an ASP.NET Dropdown List in CodeBehind After Binding

I have successfully bound an asp.net DropDownList using a jQuery ajax call. Now, I am trying to get the selected text from the code behind. How can I achieve this? <asp:DropDownList runat="server" ID="DropdownCounty" DataValueFiel ...

JavaScript Promise Chains- Issues with Functionality?

Could someone provide an explanation for why calling secondMethod in the Promise chain yields results, while calling secondMethod() does not? function firstFunction() { return new Promise(function(resolve, reject){ setTimeout(function() { ...

Persist a SQL entity to a document with the help of Node.js

I am looking for a way to store the data from the rows object either in a file or as a JSON file. app.get('/getposts', (req, res) => { mysqlConnection.query('Select * from posts', (err, rows, fields) => { if (!err) console.l ...

Is there a way to assign a value of 1 to the input-group spinner?

At first, I thought this problem would be easy to solve, but now I'm finding myself stuck. My goal is to have the input-group spinner display the value 1 when a user opens the application. <input id="option1" type="number" min="1" value ="1" ...

When it comes to successful payments, should you use `checkout.session.async_payment_succeeded` or `checkout.session.completed` in the Stripe event?

I'm feeling a little uncertain about the differences between two events: checkout.session.async_payment_succeeded & checkout.session.completed Currently, I am utilizing checkout.session.completed, but I'm wondering if checkout.session.async ...

What is the best way to customize the woocommerce.css file in the parent theme?

Currently, I have incorporated an ecommerce-friendly wordpress theme for my website in conjunction with woocommerce. To customize the design, I created a child theme and transferred the woocommerce.css file from the plugin into the css of the child theme, ...

What could be causing the unexpected text display in my shiny app despite using html tags and bootstrap?

Here is a simple example that illustrates the error I am experiencing: library(shiny) run_with_enter <- ' $(function() { var $els = $("[data-proxy-click]"); $.each( $els, function(idx, el) { var $el = $(el); var $proxy = $("#" + $el.data("proxyCl ...

In the world of Knockout JS, forget about using e.stopPropagation() because it won't

In my table, I have two actions that can be performed: Click event on the row level and click while checking a checkbox inside that row. However, when the checkbox is checked, I do not want the click event on the row to be triggered. <tbody data-bin ...

Show content to the right side of the division element

I would like to display the bold text up here, and this is my code: img{ margin-left:10px; } html <div id="wrap"> <img src="bg.jpg" /> <b class="name">WaqasTahir</b> </div> ...

Steps for designing a complete background picture

Seeking to enhance my CSS skills, I've been faced with a challenging task recently. The objective is to create a full-screen background image with centered text overlay. However, the image appears larger than the screen itself. This is my current se ...

python selenium style attribute for element

There is a snippet of HTML that resembles this: <a class="" data-style-name="Black" data-style-id="16360" "true" data-description="null"<img width="32" height="32" I am trying to extract the text "Black" from it and then click on it. However, there ...

Tips for creating a filter in React JS using checkboxes

In my current situation, I have a constant that will eventually be replaced with an API. For now, it resembles the future API in the following way: const foo = { {'id':1, 'price':200, 'type':1,}, {'id':2, &apo ...

Whenever I click the left mouse button, the website crashes

Why does clicking the left mouse button make the website scroll down? Any ideas for a solution? Check out the link here: I've tried everything since I just started working on my website. Be prepared to be shocked when you see the source code HAHAHHA ...

Leveraging the push method within AngularJS

Hello, I am currently working on setting up an eCommerce shop using Angular. Below is the code snippet I am using: var shopApp = angular.module('shopApp', ["slugifier"], function() {}); controllers.productController = function($scope,FetchFa ...