Beispiel:JS-element.attributes.html

Aus SELFHTML-Wiki
Wechseln zu: Navigation, Suche
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>DOM - Attribute finden</title>
  <link rel="stylesheet" media="screen" href="./Beispiel:SELFHTML-Beispiel-Grundlayout.css">    
  <style>


aside,
div {
	float: right;
	clear: right;
	background: #e6f2f7;
  border: 2px dotted #337599;	
	padding: 1em;
}

h2,
h3,
h4 {
background-color: #fffbf0;
  border: 2px dotted #e7c157;
	margin-top: 5px;
	max-width: 90%; 
}
img {
 	float: right;
	clear: right;
	width: 10em;
}

main { 
	border: thin dotted;
	padding: 1em;
	grid-row: 2 /5;
}

body { 
	display: grid;
	grid-template-columns: 1fr 12em;
	gap: 1em;
	max-width: 60em;
}
h1 {
	grid-column: 1 / -1;
}
	
    #output {
      margin-top: 1em;
      padding: 1em;
      border: thin solid #c82f04;
      background-color: #fed8cd;
    }
    #output pre {
      margin: 0;
			font-family: monospace;
      white-space: pre-wrap;
    }
  </style>
</head>
<body>
  <h1>DOM - Attribute finden</h1>
  <main>
  <p id="foo" class="hint">Klick' auf jedes Element, um Details über seine Attribute zu erfahren:</p>	

<p id="derText">
	Text mit <strong>fettem Text</strong> und <u>unterstrichenem Text</u> 
	<img src="https://wiki.selfhtml.org/images/4/45/SELF-Logo.svg" alt="Self-Logo" width="150" >
</p>
	<h2 id="Ober-Überschrift">Ober-Überschrift</h2>

	<h3 id="Unter-Überschrift#1">Unter-Überschrift</h3>
	<ul id="menu-items">
		<li data-info="Pizza" >Pizza</li>
		<li data-info="Pasta">Pasta</li>
		<li data-info="Ham">Prosciutto</li>
	</ul>
	<h3 id="Unter-Überschrift#2">Unter-Überschrift</h3>
	<ol id="top-three">
		<li data-info="Pizza">Pizza</li>
		<li data-info="Pasta">Pasta</li>
		<li data-info="Prosciutto">Prosciutto</li>
	</ol>
  </main>
   <div id="bar">
		<h3 id="Überschrift-div">Überschrift-Div</h3>
		<p>Absatz-Div</p>
	</div>
	<aside id="newsbox" class="alert">
		<h3 id="Überschrift-aside">Überschrift-aside</h3>
		<p>Absatz-aside</p>
	</aside> 
  <div id="output"><strong>Output:</strong> <pre></pre></div>

<script>
    document.body.addEventListener('click', function (event) {
      const clickedElement = event.target;
      const outputPre = document.querySelector('#output pre');
      let attributesInfo = '';

      if (clickedElement.attributes.length > 0) {
        attributesInfo = `Attribute von <${clickedElement.tagName.toLowerCase()}>:\n`;
        for (let attr of clickedElement.attributes) {
          attributesInfo += ` - ${attr.name}: "${attr.value}"\n`;
        }
      } else {
        attributesInfo = `Keine Attribute für <${clickedElement.tagName.toLowerCase()}> gefunden.`;
      }

      outputPre.textContent = attributesInfo;

      event.stopPropagation();
    });
  </script>
</body>
</html>