gpt4 book ai didi

javascript - 如何获取 div 或任何子元素的标记名?

转载 作者:行者123 更新时间:2023-12-03 04:19:48 25 4
gpt4 key购买 nike

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="pagehead">
<h1>Sample 1</h1>
<h1>Sample 2</h1>
<p>Thank you</p>
</div>
<button onclick="savetoJSON()">Save</button>
</body>
<script>
var count=$("#pagehead").children().length;
for(i=0;i<count;i++)
{
var ele=$("#pagehead").children()[i];
}
</script>
</html>

我想以字符串格式一一获取所有子级的标记名。我尝试了 .prop("tagName"); ,但没有效果。除此之外,我想知道如何将 [object HTMLHeadingElement] 对象转换为 string 。

最佳答案

element.tagName 是正确的选择。但请注意,每次想要访问子对象时都遍历 dom 会适得其反:

var children = $("#pagehead").children()
children.each(function(index,el){
console.log(el.tagName);
})
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="pagehead">
<h1>Sample 1</h1>
<h1>Sample 2</h1>
<p>Thank you</p>
</div>
<button onclick="savetoJSON()">Save</button>
</body>

</html>

关于javascript - 如何获取 div 或任何子元素的标记名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43999228/

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