如何访问嵌套在h1标签中的img标签元素
我试图访问嵌套在h1元素中的img元素,以便我可以更改图像的源属性。但是,我似乎无法得到firstChild,nextSibling或nextElementSibling的正确组合。如何访问嵌套在h1标签中的img标签元素
**注:**我使用的平台只允许内联样式和脚本。我不能把功能放在头上。脚本标记被忽略。
我想单击h1元素时替换图像源。这里是我的代码:
<div>
<h1 onclick="(function()
{
if(this.nextElementSibling.style.display !== 'none'){
this.nextElementSibling.style.display = 'none';
this.innerHTML = ' Click';
console.log(this.nextElementSibling.nodeName);
console.log(this.firstChild.nodeName);
}else{
this.nextElementSibling.style.display = 'block';
this.innerHTML = ' Click';
console.log(this.firstChild.nodeValue);
}
}).call(this);"> <img src="r_arrow.png" />Click</h1>
<div style="display:none; border:solid 1px red;">
Some hidden content
</div>
</div>
我用的console.log,但我仍然无法弄清楚如何获得该img标签。
您的img元素是h1的唯一子元素,但是当您使用this.firstChild
时,您可能会回到对包含
的文本节点的引用。要选择一个实际的元素,你有几种选择,包括:
this.querySelector("img").src = "whatever";
this.getElementsByTagName("img")[0].src = "whatever";
另外,我注意到你的代码,包括行:
this.innerHTML = ' Click';
这将覆盖h1元素的现有内容,取而代之的是该文本,即它将删除img元素。鉴于你的if/else的两个分支都将.innerHTML
设置为相同的字符串,我不认为你需要这样做。
这是你的代码的工作版本:
<h1 onclick="(function()
{
var next = this.nextElementSibling,
img = this.querySelector('img');
if(next.style.display !== 'none'){
next.style.display = 'none';
img.src = 'r_arrow.png';
}else{
next.style.display = 'block';
img.src = 'some_other_arrow.png';
}
}).call(this);"> <img src="r_arrow.png" />Click</h1>
有人打翻我关闭以querySelector。我的代码现在做它需要做的事情。
我的最终代码:
<div>
<h1 onclick="(function()
{
if(this.nextElementSibling.style.display !== 'none'){
this.nextElementSibling.style.display = 'none';
this.querySelector('img').setAttribute('src','r_arrow.png');
console.log(this.nextElementSibling.nodeName);
console.log(this.firstChild.nodeName);
}else{
this.nextElementSibling.style.display = 'block';
this.querySelector('img').setAttribute('src','d_arrow.png');
}
}).call(this);"> <img src="r_arrow.png" />Click</h1>
<div style="display:none; border:solid 1px red;">
Some hidden content
</div>
</div>
有人吗?那是我,但我删除了我的评论,并将其作为答案。请注意,你不需要'.setAttribute()'来设置'src',你可以说'.src =“something”;' – nnnnnn
WAT?什么样的平台力量在HTML属性值中评估JS。这很重要。 – Sukima
这是代码以前工作的方式剩下的。大部分形式,您的解决方案工作。我只需要添加setAttribute()方法来更改src属性的值。 –