Reputation: 12858
I have a page containing the following div element:
<div id="myDiv" class="myDivClass" style="">Some Value</div>
How would I retrieve the value ("Some Value") either through JQuery or through standard JS? I tried:
var mb = document.getElementById("myDiv");
But the debugger console shows "mb is null". Just wondering how to retrieve this value.
---- UPDATE ---- When I try the suggestion I get: $ is not a function
This is part of a JQuery event handler where I am trying to read the value when I click a button. The handler function is working but it can't interpret the jQuery value it seems:
jQuery('#gregsButton').click(function() {
var mb = $('#myDiv').text();
alert("Value of div is: " + mb.value);
});
Upvotes: 42
Views: 308038
Reputation: 11
You can do get id value by using
test_alert = $('#myDiv').val();
alert(test_alert);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv"><p>Some Text</p></div>
Upvotes: 0
Reputation: 52523
$('#myDiv').text()
Although you'd be better off doing something like:
var txt = $('#myDiv p').text();
alert(txt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv"><p>Some Text</p></div>
Make sure you're linking to your jQuery file too :)
Upvotes: 76
Reputation: 1390
your div looks like this:
<div id="someId">Some Value</div>
With jquery:
<script type="text/javascript">
$(function(){
var text = $('#someId').html();
//or
var text = $('#someId').text();
};
</script>
Upvotes: 7
Reputation: 36749
myDivObj = document.getElementById("myDiv");
if ( myDivObj ) {
alert ( myDivObj.innerHTML );
}else{
alert ( "Alien Found" );
}
Above code will show the innerHTML, i.e if you have used html tags inside div then it will show even those too. probably this is not what you expected. So another solution is to use: innerText / textContent property [ thanx to bobince, see his comment ]
function showDivText(){
divObj = document.getElementById("myDiv");
if ( divObj ){
if ( divObj.textContent ){ // FF
alert ( divObj.textContent );
}else{ // IE
alert ( divObj.innerText ); //alert ( divObj.innerHTML );
}
}
}
Upvotes: 28
Reputation: 4771
You could use
jQuery('#gregsButton').click(function() {
var mb = jQuery('#myDiv').text();
alert("Value of div is: " + mb);
});
Looks like there may be a conflict with using the $. Remember that the variable 'mb' will not be accessible outside of the event handler. Also, the text() function returns a string, no need to get mb.value.
Upvotes: 2
Reputation: 1456
if you div looks like this:
<div id="someId">Some Value</div>
you could retrieve it with jquery like this:
$('#someId').text()
Upvotes: 16