如何遍历所有 <p> 元素

How can I loop through all <p> elements?

本文关键字:元素 何遍历 遍历      更新时间:2023-09-26

我想遍历文档中的所有段落元素并调整它们的html。目前我使用一些jquery:

console.log("loop through <p> elements");    
$("p").each(function()
{
    console.log("next <p> element with id: " + this.id);
});

但是,控制台中仅显示"循环段落元素",并且我的身体中有一些具有唯一ID的段落元素:

<body>
    <p id="para1"> paragraph 1 </p>
    <p id="para2"> paragraph 2 </p>     
    <p id="para3"> paragraph 3 </p> 
</body>

我希望这是 .each() 循环的某种语法错误,并且有人可以纠正我,任何帮助将不胜感激。

你的代码应该是:

$("p").each(function()
{
    console.log("next <p> element with id: " + $(this).attr('id'));
});

因为$(this).id不存在,或者this.id也是有效的。

现场演示

你应该

使用

$("p").each(function() {
    console.log("next <p> element with id: " + this.id);
});

idElement实例的属性,例如 this .如果将其包装到 jQuery 元素中,它将不再具有 id 属性,因此您必须使用 jQuery 方法获取它,例如 $(this).prop('id') 。不过,这是不必要的。

您是否收到错误:未捕获的引用错误:未定义 $?如果是这种情况,请加载 JQuery 库。将其添加到 html 文档的头部。

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

jQuery 对象没有 id 属性。若要获取元素的 ID,请使用 $(this).attr('id')

如果它仍然没有循环遍历标签,那么它可能在 DOM 有机会完成加载之前就正在运行。将代码放在就绪处理程序中将延迟执行,直到 DOM 完全加载:

$(document).ready(function() {
    console.log("loop through <p> elements");    
    $("p").each(function()
    {
        console.log("next <p> element with id: " + $(this).attr('id'));
    });
});