Javascript DOM HTML HTMLCollection namedItem() Method

Introduction

Get the content of the P element with ID.

Click the button to return the content of the P element with ID myElement:

View in separate window

<!DOCTYPE html>
<html>
<body>
<p id="myElement">The namedItem() method returns the element with the specified ID or name.</p>
<button onclick="myFunction()">Alert innerHTML of P</button>

<p id="demo"></p>

<script>
function myFunction() {/*from  w  ww. j av  a 2 s.co  m*/
  var x = document.getElementsByTagName("P").namedItem("myElement");
  document.getElementById("demo").innerHTML = x.innerHTML;
}
</script>

</body>
</html>

The namedItem() method returns the element with the specified ID, or name as an HTMLCollection.

namedItem(name);

Parameter Values

Parameter Description
name Required. The value of the id attribute, or name attribute, of the element to get.

The namedItem() method returns an Element object, representing the element at with specified ID or name.

The namedItem() method returns null if the element does not exist.

A shorthand method can also be used, and will produce the same result:

View in separate window

<!DOCTYPE html>
<html>
<body>
<p id="myElement">The namedItem() method returns the element with the specified ID or name.</p>
<button onclick="myFunction()">Alert innerHTML of P</button>
<p id="demo"></p>
<script>
function myFunction() {//  w ww . jav  a 2 s.  c o m
  var x = document.getElementsByTagName("P")["myElement"];
  document.getElementById("demo").innerHTML = x.innerHTML;
}
</script>

</body>
</html>



PreviousNext

Related