Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

javascript - 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); 
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$('#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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...