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); });
To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.
To set or get the text value of input or textarea elements, use the . val() method. To get the value of a script element, use the . html() method.
jQuery val() Method The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.
First, use the html() function instead of the text() function. Second, point your selector to the right node, something like . portlet-content . content_regular table .
$('#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 :)
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 ); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With