how to assign a css class to title of svg element using javascript?

后端 未结 2 1571
傲寒
傲寒 2021-01-28 12:10

I have used this: That does not work. I have added both of urs suggestion.. but it did not work!

svg
{
 width:720px;
 height:50px;
 border:#999999 solid 2px;
}
.         


        
相关标签:
2条回答
  • 2021-01-28 12:47

    You can add it as below:

    title.classList.add("tooltip");
    

    Here is the DEMO

    UPDATE:

    Check this Updated Demo

    There were some console errors which I have cleared.

    Just copy and paste the javascript part as it is in your page and see that class will be added now. One major change was that you were adding class to title along with . like title.classList.add('.tooltip'); but it should have been without . like title.classList.add('tooltip'); Check the demo and let me know!!

    0 讨论(0)
  • 2021-01-28 12:49

    1.) this element has not been inserted in the DOM so you cannot use document.getElementByTagName('title')
    2.) document.getElementByTagName('title')[0] return the title tag of the document which is used to specify the title of the document/page.

    what you should do is this:

    var title = document.createElementNS('http://www.w3.org/2000/svg', 'title');
    title.textContent = data[i].title;//JSON object That works
    title.setAttribute('class','tooltip');
    

    Assign the attribute on the reference of the element you just created i.e title and not document.getElementsByTagName('title')[0].

    0 讨论(0)
提交回复
热议问题