简体   繁体   中英

How to get value from a dynamic element

I need to get the value from a "p" element, I draw this "p" with jQuery and it's ok, then I have a button and when I click on it I want to display the value from "p" element but I don't get any information, here is a simple code example:

 $(document).ready(function() { $('#c').click(function() { var p = $('#p1').val(); alert(p); }); draw(); }); function draw() { var html = ""; html += '<p id="p1">Hi</p>'; $('#d').html(html); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="c">Click</button> <hr /> <div id="d"> </div> 

How can I solve this? I don't get any console error.

Change :

var p = $('#p1').val();

To :

var p = $('#p1').text();

.val() only returns the value from input , textarea and select elements. If you just want to read the content of an element, you should use .text() or .html() . The first returns just the text, and the second – HTML content of an element.

Here is the quote from jQuery

The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.

So as @ehsan suggested, use .text() method if you want to get content as text.

.val() is used to get the value of input , select and textarea elements.

If you want to get the text inside an element (eg: div , p , etc), you need to use .text() .

So, in your case, you need to change this:

var p = $('#p1').val();

for this:

var p = $('#p1').text();

Note: If you want the full html code inside an element, you need to use .html() .

Sources:

你也可以使用var p = $('#p1').html();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM