<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]对象转换为字符串。
答案 0 :(得分:1)
element.tagName
是要走的路。但请注意,每次想要访问孩子时遍历dom都会适得其反:
var children = $("#pagehead").children()
children.each(function(index,el){
console.log(el.tagName);
})
&#13;
<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>
&#13;
答案 1 :(得分:0)
使用
Element.tagName
属性,它返回元素的名称。
var count = $("#pagehead").children().length;
for (i = 0; i < count; i++) {
var ele = $("#pagehead").children()[i];
console.log(ele.tagName);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="pagehead">
<h1>Sample 1</h1>
<h1>Sample 2</h1>
<p>Thank you</p>
</div>
优化选项:
var pageheadChildren = $("#pagehead").children();
for (var i = 0, len = pageheadChildren.length; i < len; i++) {
console.log(pageheadChildren[i].tagName);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="pagehead">
<h1>Sample 1</h1>
<h1>Sample 2</h1>
<p>Thank you</p>
</div>
使用jQuery.prop
:
$("#pagehead").children().each(function() {
console.log($(this).prop('tagName'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="pagehead">
<h1>Sample 1</h1>
<h1>Sample 2</h1>
<p>Thank you</p>
</div>
答案 2 :(得分:0)
您可以使用.each()
遍历元素并简化代码。
$("#pagehead").children().each(function() {
console.log($(this).prop('tagName'));
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pagehead">
<h1>Sample 1</h1>
<h1>Sample 2</h1>
<p>Thank you</p>
</div>
&#13;
答案 3 :(得分:0)
也许你试过$(el)[i].prop('tagName')
会失败。尝试循环元素并列出$(el).prop('tagName')
function savetoJSON() {
$("#pagehead > *").each(function() {
console.log($(this).prop('tagName'));
});
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="pagehead">
<h1>Sample 1</h1>
<h1>Sample 2</h1>
<p>Thank you</p>
</div>
<button onclick="savetoJSON()">Save</button>
&#13;
答案 4 :(得分:0)
使用map()
生成列表作为数组
var tags = $('#pagehead').children().map(function(){
return this.tagName;
}).get().join()
console.log(tags);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pagehead">
<h1>Sample 1</h1>
<h1>Sample 2</h1>
<p>Thank you</p>
</div>