1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
| <!DOCTYPE HTML>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Récupération « arbre » des headings</title>
<meta name="Author" content="NoSmoking">
<style>
* {
margin: 0;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
min-height: 100%;
font: 1em/1.5 Verdana,sans-serif;
}
main {
display: block;
margin: 0 auto;
max-width: 60em;
}
header h1 {
color: #069;
font-size: xx-large;
}
.row {
display: table-cell;
border: none !important;
vertical-align: top;
width: 28em;;
}
h1, h2, h3, h4, h5, h6 {
margin: 0;
font-size: 1.5em;
}
section, article, div {
margin: .5em 1em;
padding: 0 .5em;
border: 1px solid #CCC;
}
section:hover, article:hover, div:hover {
border: 1px solid #069;
}
ul {
margin: .5em 1em;
padding-left: 1.5em;
border: 1px solid #ABC;
line-height: 1.5em;
}
button {
line-height: 2em;
min-width: 20em;
font-size: inherit;
cursor: pointer;
}
</style>
</head>
<body>
<main>
<header>
<h1>Récupération « arbre » des headings</h1>
</header>
<div class="row">
<div>
<h1>Titre 1.1</h1>
<p>Du texte ...</p>
<h2>Titre 2.1</h2>
<section>
<h1>Titre 1.2</h1>
<p>Du texte ...</p>
<h4>Titre 4.1</h4>
<article>
<h5>Titre 5.1</h5>
<p>Du texte ...</p>
</article>
<h3>Titre 3.1</h3>
<p>Du texte ...</p>
</section>
<section>
<h1>Titre 1.4</h1>
Du texte ...
</section>
</div>
<div>
<h1>Titre 1.3</h1>
</div>
</div>
<div class="row" id="result">
</div>
<button onclick="createListHeading()">createListHeading</button>
</main>
<script>
var selectorHeadings = "h1,h2,h3,h4,h5,h6";
function findListHeading(node) {
var oHs = node.querySelectorAll(selectorHeadings);
var i;
var nb = oHs.length;
var elem;
var parent;
var result = [];
for (i = 0; i < nb; i += 1) {
elem = oHs[i];
// test si déjà traité
if (!elem.getAttribute("flag")) {
parent = elem.parentNode;
// pris en compte si même parent
if (parent === node) {
result.push("<LI><" + elem.tagName + "> " + elem.textContent);
// marque comme traité
elem.setAttribute("flag", "true");
}
// on y retourne
else {
result.push("<UL>" + findListHeading(parent) + "</UL>");
}
}
}
return result.join("");
}
function createListHeading() {
// récup. de la liste
var html = findListHeading(document.querySelector("body"));
// affichage
document.querySelector("#result").innerHTML = html;
// on clear le flag
var oElems = document.querySelectorAll("[flag]");
Array.prototype.slice.call(oElems).map(function (elem) {
elem.removeAttribute("flag");
});
}
</script>
</body> |
Partager