I have the following code:
function obtener(){
var contador = 1;
$("body").each(function(){
console.log(contador + " " + $(this).text() + "\n");
console.log("----------------------------------\n");
contador++;
});
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<ul class="level-1">
<li class="item-i">I</li>
<li class="item-ii">II
<ul class="level-2">
<li class="item-a">A</li>
<li class="item-b">B
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
</li>
<li class="item-c">C</li>
</ul>
</li>
<li class="item-iii">III</li>
</ul>
<input type="submit" onclick="obtener();" value="Obtener">
</body>
</html>
The code first shows an organized list, with certain texts and bullets, in short, the one in this example is only demonstrative.
What I intend to do is obtain the text of each of the elements contained within the label individually.
I tried the .each function of jquery , as follows:
$("body").each(function(){
console.log(contador + " " + $(this).text() + "\n");
console.log("----------------------------------\n");
});
But, when the console.log
message is printed, everything is displayed as a single text, that is, instead of being printed like this:
I
---------
II
---------
A
---------
B
---------
It is printing like this:
I
II
A
B
1
2
3
---------------------
I have not found documentation about it, other than jQuery and the management of the .each function, but I do not understand why it prints everything as a single text, since it "runs through" each of the elements contained in the selector.