这是html(在多个位置出现,但每种外观应区别对待):
<div class="foot-nav-heading">Click me!</div>
<div class="textwidget">
<ul class="quick-link accordion-content">
<li>Test</li>
</ul>
</div>
这是JavaScript代码:
var accordions = document.getElementsByClassName("foot-nav-heading");
for (var i = 0; i < accordions.length; i++) {
accordions[i].onclick = function() {
this.classList.toggle('is-open');
var content = this.nextElementSibling;
if (content.style.maxHeight) {
// accordion is currently open, so close it
content.style.maxHeight = null;
} else {
// accordion is currently closed, so open it
content.style.maxHeight = content.scrollHeight + "px";
}
}
}
我想在“ div.textwidget”元素内定位“ ul”。我试过了
var content = this.next.(".text-widget").find(".accordion-content")
但这是行不通的。
提前致谢!
最佳答案
您的代码有效!问题不在于兄弟,问题在于您不能将css height设置为null
var accordions = document.getElementsByClassName("foot-nav-heading");
for (var i = 0; i < accordions.length; i++) {
accordions[i].onclick = function() {
this.classList.toggle('is-open');
var content = this.nextElementSibling;
if (content.style.maxHeight != "0px") {
// accordion is currently open, so close it
content.style.maxHeight = "0px";
} else {
// accordion is currently closed, so open it
content.style.maxHeight = "200px";
}
}
}
<div class="foot-nav-heading">Click me!</div>
<div class="textwidget">
<ul class="quick-link accordion-content">
<li>Test</li>
</ul>
</div>
Here is the javascript code:
<div class="foot-nav-heading">Click me!</div>
<div class="textwidget">
<ul class="quick-link accordion-content">
<li>Test</li>
</ul>
</div>
Here is the javascript code:
编辑:
您尝试使用代码得到的是nextSibling。但是您可能会有带有回车符的多余textnode尝试以下代码段:
document.querySelectorAll(".textwidget")[0].childNodes.forEach(function(el){
console.log(el.nodeName,el.nodeType);
});
<div class="foot-nav-heading">Click me!</div>
<div class="textwidget">
<ul class="quick-link accordion-content">
<li>Test</li>
</ul>
</div>
因此,尝试直接定位是有风险的(在您的示例中,您可以使用
content.childNodes[1]
获得所需的内容,但是如果您不知道html的编写方式,则很危险。可能是content.childNodes[0]
而没有回车符)。因此,最好的选择是解析childNodes并在它们完全满足条件时在数组中设置变量或push元素。在您的情况下:var ul;
content.forEach(function(el){
if (el.nodeName === 'UL') ul = el;
}
或从nodelist创建一个数组以过滤所需的节点:
var ul = Array.from(document.querySelectorAll(".textwidget")[0].childNodes).filter(function(el) {if(el.nodeName == 'UL') return el});
// or use es6 features
// var ul = [...document.querySelectorAll(".textwidget")[0].childNodes].filter(e => e.nodeName == 'UL');
console.log(ul[0]);
<div class="foot-nav-heading">Click me!</div>
<div class="textwidget">
<ul class="quick-link accordion-content">
<li>Test</li>
</ul>
</div>
关于javascript - 我想在不使用类或ID的情况下将目标元素定位在下一个同级父对象中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53838171/