'How to get value of the HTML element? [duplicate]
I have a question, how can i get value of the element using javaScript with Jquery? I have tried this and error sad .val() is not a function and i could not find any solution. Everithink i found told me it is not a function. Thanks for reply.
const btn = $('.btn');
let example = $('#example');
let result = $('#result');
var test = btn.value;
btn.on('click', function(){
console.log($(this).val());
})
.btn{
border-radius: 5px;
margin-top: 3vh;
float: left;
margin-left: 4%;
width: 20%;
height: 12vh;
background: red;
line-height:12vh;
text-align: center;
font-size:300%;
font-weight: bold;
}
<div class="btn" val="1">1</div>
**
Solution 1:[1]
you can use $(this).attr for this
val() works only on input or buttons
const btn = $('.btn');
let example = $('#example');
let result = $('#result');
var test = btn.value;
btn.on('click', function(){
console.log($(this).attr('val'));
})
.btn{
border-radius: 5px;
margin-top: 3vh;
float: left;
margin-left: 4%;
width: 20%;
height: 12vh;
background: red;
line-height:12vh;
text-align: center;
font-size:300%;
font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="btn" val="1">1</div>
**
Solution 2:[2]
To get innerHTML you can use this plain JS code
<div id="myButton" class="btn" val="1">1</div>
const button = document.getElementById('myButton');
const value = value.innerHTML;
And you should have value of it
:)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | R4ncid |
| Solution 2 | OceanTechnic |
