简体   繁体   中英

How do I get a value of a <span> using jQuery?

This is basic.

How do I get the value 'This is my name' of the above span?

<div id='item1'>
<span>This is my name</span>
</div>

I think this should be a simple example:

$('#item1 span').text();

or

$('#item1 span').html();
$("#item1 span").text();

假设你打算让它读取 id="item1",你需要

$('#item1 span').text()

Since you did not provide an attribute for the 'item' value, I am assuming a class is being used:

<div class='item1'>
  <span>This is my name</span>
</div>

alert($(".item span").text());

Make sure you wait for the DOM to load to use your code, in jQuery you use the ready() function for that:

<html>
 <head>
  <title>jQuery test</title>
  <!-- script that inserts jquery goes here -->
  <script type='text/javascript'>
    $(document).ready(function() { alert($(".item span").text()); });
  </script>
</head>
<body>
 <div class='item1'>
   <span>This is my name</span>
 </div>
</body>

$('#item1').text(); or $('#item1').html(); works fine for id="item1"

在 javascript 中,您不会使用document.getElementById('item1').innertext吗?

     $('span id').text(); worked with me

$('#id span').text()就是答案!

You could use id in span directly in your html.

<span id="span_id">Client</span>

Then your jQuery code would be

$("#span_id").text();

Some one helped me to check errors and found that he used val() instead of text(), it is not possible to use val() function in span. So

$("#span_id").val();

will return null.

$('#item1 span').html(); Its working with my code

VERY IMPORTANT Additional info on difference between .text() and .html():

If your selector selects more than one item, eg you have two spans like so <span class="foo">bar1</span> <span class="foo">bar2</span> ,

then

$('.foo').text(); appends the two texts and give you that; whereas

$('.foo').html(); gives you only one of those.

<script>
    $(document).ready(function () {

            $.each($(".classBalence").find("span"), function () {
            if ($(this).text() >1) {
                $(this).css("color", "green")

            }
            if ($(this).text() < 1) {
                $(this).css("color", "red")
                $(this).css("font-weight", "bold")
            }
        });

    });
    </script>

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