Javascript - getElementsByTagName
Phương thức getElementsByTagName() trong JS
Lấy phần tử theo tên, chính là thuộc tính name trong thẻ.
Cú pháp:
document.getElementsByTagName("name")
Tên thẻ là bắt buộc
Trong ví dụ này, chúng ta sẽ đếm tổng số đoạn văn bản được sử dụng trong đối tượng document . Để làm điều này, chúng ta đã gọi phương thức document.getElementsByTagName ("p") trả lại tổng số đoạn văn.
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by getElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
Trong ví dụ này, chúng ta sẽ tính tổng số thẻ h2 và h3 được sử dụng trong đối tượng.
<script type="text/javascript">
function counth2(){
var totalh2=document.getElementsByTagName("h2");
alert("total h2 tags are: "+totalh2.length);
}
function counth3(){
var totalh3=document.getElementsByTagName("h3");
alert("total h3 tags are: "+totalh3.length);
}
</script>
<h2>This is h2 tag</h2>
<h2>This is h2 tag</h2>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<button onclick="counth2()">count h2</button>
<button onclick="counth3()">count h3</button>