Javascript getElementsByClassName和…;ByTagName,<;路径>;及<;svg>;,使用onclick="&引用;改变风格 希望我的问题达到标准(我整个上午都在研究,所以我希望我已经足够深入了)

Javascript getElementsByClassName和…;ByTagName,<;路径>;及<;svg>;,使用onclick="&引用;改变风格 希望我的问题达到标准(我整个上午都在研究,所以我希望我已经足够深入了),javascript,css,svg,onclick,Javascript,Css,Svg,Onclick,我正在学习所有这些新的html5,因此我可以使用SVG、和CSS3制作交互式图形,并使用一些Javascript。我正试图摆脱我在做事情时使用的丑陋、冗余的函数,并很好地整理我的代码 我在为的onclick事件创建javascript以更改使用document.getElementsByClassName包含SVG中所有路径的类的样式时遇到问题。 我已经使用了document.getElementById,但是我想一次影响多个路径,而不必浪费大量的行来将数百个ID抓取到一个var或类似的东西中

我正在学习所有这些新的html5,因此我可以使用SVG、
和CSS3制作交互式图形,并使用一些Javascript。我正试图摆脱我在做事情时使用的丑陋、冗余的函数,并很好地整理我的代码

我在为
的onclick事件创建javascript以更改使用
document.getElementsByClassName
包含SVG中所有路径的类的样式时遇到问题。 我已经使用了
document.getElementById
,但是我想一次影响多个路径,而不必浪费大量的行来将数百个ID抓取到一个var或类似的东西中

这是到目前为止我的代码,第一个按钮有效,接下来的两个是我遇到的问题

<head>
<style>
  .pathclass { 
fill:none;
stroke:#ffffff;
stroke-width:4; }
</style></head>

<body>

<button onclick="document.getElementById('pathId').style.stroke = '#000000';" />
<br />
<button onclick="document.getElementsByClassName('pathClass').style.stroke = '#000000';" />
<br />
<button onclick="document.getElementsByTagName('path').style.stroke = '#000000';" />

<svg><g><path id="pathId" class="pathclass" /></g></svg>

.pathclass{
填充:无;
冲程:#ffffff;
笔划宽度:4;}



接下来,我想使用类似于
document.getElementsTagName('path')的东西自动设置所有
classNames
,当执行
document.getElementsByClassName
时,它返回一个节点列表。节点列表类似于数组,必须对其进行迭代才能应用样式:

// collect all nodes with class='oldclass'
var nodes = document.getElementsByClassName('oldclass');
// loops to get each node in our NodeList
for (var i=0, length = nodes.length; i < length; i++) {
   // i starts at 0 and increments with each loop (i++ increments i on each iteration)
   // it won't stop until it reaches the number of nodes (i < length)
   // so on the first iteration it will be nodes[0]
   // which is your first element, the second time
   // it will be nodes[1] which is your second, and so on
   nodes[i].style.stroke = "black";
}

var paths = document.getElementsByTagName('path');
for (var i=0, length = paths.length; i < length; i++) {
   paths[i].className = "newclass";
}

document.querySelector和document.querySelector感谢Geuis。我查过了,但它说它只返回与选择器匹配的第一个元素。我正在寻找一种方法来同时选择具有相同类的所有元素。@Geuis的此功能类似于@Duopixel的答案?文档中提到的
d3.selectAll
。querySelectorAll('.yourclass')//返回包含所有元素的数组。我提到这两件事是为了让你能更清楚地了解,答案就在这里!现在我要做的就是理解它XD。这是假设所有路径都是:1)不在单独的文档中;2) 现在我的问题是,如何使用相同的设置来执行
节点[i].className=“newclass”
部分,使用
document.getElementsByTagName('path')
d3.selectAll(".oldclass").style("stroke", "black");
d3.selectAll("path").attr("class", "newclass");