gpt4 book ai didi

javascript - 段落可以作为父元素吗?

转载 作者:行者123 更新时间:2023-12-02 15:11:14 26 4
gpt4 key购买 nike

应该提及:我不是最有经验的网络程序员。尽管如此:目前正在处理一些前端的事情。

昨天我编写了一些 JavaScript,但结果并不符合我的预期。

我做了这个演示:

每个段落都包含一个标题和一些文字。这些段落包含在 div 容器内。

<div class="container">
<p class="paragraph">
<h3 class="headline">Some headline ...</h3>
<span>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. </span>
</p>

<p class="paragraph">
<h3 class="headline">Another headline ...</h3>
<span>Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus.</span>
</p>

<!-- More paragraph-container ... -->
</div>

假设我引用了第一个标题,并且想要获取第一个段落标签的类名。

我想要这样的事情:

// Get a reference to the first headline element.
var headline = document.getElementsByClassName('headline')[0];
// Access the parent of the headline element.
console.log(headline.parentNode.className);
// Result is: container

我期望返回“段落”,因为该段落包含标题。相反,我得到了 div 的类名。

谁能解释一下这种行为吗?

最佳答案

将标题元素( <h1><h2> 等)放入段落元素内不是有效的 html。

您的浏览器可能正在关闭<h3>之前的段落元素。元素,因此是 <h3> 的父元素成为你的container <div> ,

关于javascript - 段落可以作为父元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34783663/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com