Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a Div Value in JQuery

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);  }); 
like image 984
GregH Avatar asked Dec 01 '09 17:12

GregH


People also ask

How to get value from div jQuery?

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.

How to get text of element jQuery?

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.

What does val() return in jQuery?

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.

How do I get HTML inside a div using jQuery?

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 .


2 Answers

$('#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 :)

like image 199
Jason Avatar answered Sep 28 '22 20:09

Jason


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 );                 }              }           } 
like image 40
Rakesh Juyal Avatar answered Sep 28 '22 20:09

Rakesh Juyal