Code
var elementos = $(".boton").map(function() {
return $(this).html();
}).get();
console.log(elementos);
.boton {
background-color: #2980b9;
color: #ecf0f1;
width: 100px;
height: 30px;
text-align: center;
}
.elemento {
background-color: #ecf0f1;
color: #2980b9;
width: 100px;
height: 30px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boton">
<a>UNO</a>
</div>
<div class="boton">
<a>DOS</a>
</div>
<div class="elemento">
<a>TRES</a>
</div>
<div class="boton">
<a>CUATRO</a>
</div>
Explanation
Reviewing what you propose, about getting items using a selector based on the name of the class, I could find the following:
- Using
$(this)
to access the element
- Instead of using the
.innerHTML
parameter, use the .html () method.
Maybe this is an incompatibility problem in the browser where you are executing the code, because if you try in another way:
var elementos = $(".boton").map(function() {
return this.innerHTML;
}).get();
console.log(elementos);
.boton {
background-color: #2980b9;
color: #ecf0f1;
width: 100px;
height: 30px;
text-align: center;
}
.elemento {
background-color: #ecf0f1;
color: #2980b9;
width: 100px;
height: 30px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boton">
<a>UNO</a>
</div>
<div class="boton">
<a>DOS</a>
</div>
<div class="elemento">
<a>TRES</a>
</div>
<div class="boton">
<a>CUATRO</a>
</div>
If you notice you will get the same result you get using the .html () method. jQuery
Note: You must take into account that if you are getting the innerHTML of an element, you will get the literal string of html of what is inside the element, in example I used <a>
and the innerHTML will return the text content between <a>
, but if you need to get all the composition of the element, you can use outerHTML
.
Update
If what you need is to access each of the properties of the HTML element, it would also be useful to use .each :
$(".boton").each(function() {
$(this).css("background-color", "red");
}).get();
.boton {
background-color: #2980b9;
color: #ecf0f1;
width: 100px;
height: 30px;
text-align: center;
}
.elemento {
background-color: #ecf0f1;
color: #2980b9;
width: 100px;
height: 30px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boton">
<a>UNO</a>
</div>
<div class="boton">
<a>DOS</a>
</div>
<div class="elemento">
<a>TRES</a>
</div>
<div class="boton">
<a>CUATRO</a>
</div>
In this example we have referenced each of the html nodes, directly accessing them through jQuery and we have modified the background color that it had initially.