How to get div id element in Javascript

In JavaScript, you can use getElementById() fucntion to get any prefer HTML element by providing their tag id. Here is a HTML example to show the use of getElementById() function to get the DIV tag id, and use InnerHTML() function to change the text dynamically.

HTML…


<html>
<head>
<title>getElementById example</title>

<script type="text/javascript">

function changeText(text)
{
 elem = document.getElementById('textid');
 elem.innerHTML = text;
}
</script>
</head>

<body>
<div id='textid'>I'm a Text</div>
<button onclick="changeText('Mkyong1');">Mkyong1</button>
<button onclick="changeText('Mkyong2');">Mkyong2</button>
</body>
</html>
  1. If button “Mkyong1” is clicked, the content of the div element, with an Id of “textid”, will be changed to “Mkyong1”.
  2. If button “Mkyong2” is clicked, the content of the div element, with an Id of “textid”, will be changed to “Mkyong2”.

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Edna Ferg
5 years ago

The example shows how to get an element knowthing the id. It does not show
how to get the id of an element one has accessed by other means.

Keith
14 years ago

Hi Mkyong,
Thanks dude.
This piece of code has being killing me for 6 hours

 var flight = document.getElementById("fltDet").innerHTML; 

If you ever in Ireland there is a pint of Guinness with your name on it.
Keith

Luis Castro
9 years ago
Reply to  Keith

Gracias a ti pude resolver un gran problme Keith