[英]How to get tagname of child element of a div or any?
<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");
獲取所有子項的標記名。我嘗試了.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>
使用
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>
您可以使用.each()
遍歷元素並稍微簡化代碼。
$("#pagehead").children().each(function() { console.log($(this).prop('tagName')); })
<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>
也許您嘗試$(el)[i].prop('tagName')
失敗的$(el)[i].prop('tagName')
。 嘗試僅循環您的元素並列出$(el).prop('tagName')
function savetoJSON() { $("#pagehead > *").each(function() { console.log($(this).prop('tagName')); }); }
<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>
使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.