Skip to main content
1-Visitor
February 13, 2020
Question

how to get access of html element in javascript

  • February 13, 2020
  • 1 reply
  • 3297 views

I have added dynamic svg element (below is the code) and now wanted to access circle element by id to update its css.

 

// Circle New
xmlsrc_in = '<circle id="bar" r="30" cx="100" cy="100" transition="stroke-dashoffset 1s linear" stroke="green" stroke-width="1em" fill="transparent" stroke-dasharray="565.48" stroke-dashoffset="0"></circle>'


xmlsrc=xmlsrc+'<svg class="svg" xmlns="http://www.w3.org/2000/svg" height="200" width="200" viewPort="0 0 100 100" version="1.1">\n'

xmlsrc=xmlsrc+ xmlsrc_in

xmlsrc=xmlsrc+'</svg>'

 

Can someone tell me how could I access circle element by id/class etc (bar) in javascript function?

 

1 reply

18-Opal
February 13, 2020

In the general case, you should be able to use document.querySelector() to grab an element in the document, and then you can access its .style property to modify style attributes, something like this:

document.querySelector("#bar").style.color = "#ff0000";

However, I don't know to what extent SVG content can be modified in this way. SVG rendering is usually its own thing separate from general HTML rendering. Instead of CSS properties, you may need to modify SVG markup attributes directly to get the desired effect. For example, if you want to make your generated "bar" element red instead of green, you might need to change the stroke attribute directly, like so:

document.querySelector("#bar").setAttribute("stroke","red");

 

1-Visitor
February 19, 2020

@ClayHelberg thanks for the reply.

 

I have tried both the methods but querySelector is returning a null object.

Unless and until I get an Html object, I can not apply any CSS or change the inline style.

 

Please see the attached screenshot of the console.

18-Opal
February 19, 2020

It looks like it's doing what I was afraid of, rendering the SVG separately and then just treating it as image data in the DOM. If you look at the document tree in the browser debugger, you'll see that there's no SVG markup there, it just gets rasterized and then thrown away apparently.

 

To do what you want, you might need to try a different approach, such as:

  • If there are Unicode characters that are pretty close to the image you are using, you would have better CSS styling options, e.g. U+1F6AB = 🚫
  • You could simply use multiple image files, one for each appearance needed, and update the "src" attribute to switch them out
  • You could try loading the SVG markup into a TML widget, and then use Javascript to copy it into a container in the document to display it. Then you should be able to access the SVG markup with Javascript to modify attributes. A quick test confirms that this works for 2D widgets, but I couldn't get it to work for a 3D image widget.