JavaTutorial DOM script con esempio

In cosa consiste il DOM JavaCopione?

JavaLo script può accedere a tutti gli elementi di una pagina web utilizzando il Document Object Model (DOM). Infatti, il browser web crea un DOM della pagina web quando la pagina viene caricata. Il modello DOM è creato come un albero di oggetti come questo:

DOM dentro JavaCopione

Come utilizzare DOM ed eventi

Utilizzando DOM, JavaLo script può eseguire più attività. Può creare nuovi elementi e attributi, modificare gli elementi e gli attributi esistenti e persino rimuovere elementi e attributi esistenti. JavaCopione può anche reagire agli eventi esistenti e creare nuovi eventi nella pagina.

getElementById, esempio innerHTML

  1. getElementById: per accedere agli elementi e agli attributi il ​​cui ID è impostato.
  2. innerHTML: per accedere al contenuto di un elemento.

Prova tu stesso questo esempio:

<html>
<head>
	<title>DOM!!!</title>
</head>
<body>
  <h1 id="one">Welcome</h1>
  <p>This is the welcome message.</p>
  <h2>Technology</h2>
  <p>This is the technology section.</p>
  <script type="text/javascript">
		var text = document.getElementById("one").innerHTML;
		alert("The first heading is " + text);
  </script>
</body>
</html>

getElementsByTagName Esempio

getElementsByTagName: per accedere a elementi e attributi utilizzando il nome del tag. Questo metodo restituirà un file schieramento di tutti gli elementi con lo stesso nome di tag.

Prova tu stesso questo esempio:

<html>
<head>
	<title>DOM!!!</title>
</head>
<body>
  <h1>Welcome</h1>
  <p>This is the welcome message.</p>
  <h2>Technology</h2>
  <p id="second">This is the technology section.</p>
  <script type="text/javascript">
	var paragraphs = document.getElementsByTagName("p");
    alert("Content in the second paragraph is " + paragraphs[1].innerHTML);
    document.getElementById("second").innerHTML = "The orginal message is changed.";
  </script>
</body>
</html>

Esempio di gestore eventi

  1. createElement: per creare un nuovo elemento
  2. rimuoviChild: rimuove un elemento
  3. Puoi aggiungere un gestore di eventi a un particolare elemento come questo:
document.getElementById(id).onclick=function()
{
    lines of code to be executed
}

OR

document.getElementById(id).addEventListener("click", functionname)

Prova tu stesso questo esempio:

<html>
<head>
	<title>DOM!!!</title>
</head>
<body>
  <input type="button" id="btnClick" value="Click Me!!" />
  <script type="text/javascript">
	document.getElementById("btnClick").addEventListener("click", clicked);
    function clicked()
    {
   		 alert("You clicked me!!!");
    }	
  </script>
</body>
</html>