简体   繁体   中英

jQuery - Change text of inner <span name=“bar”> element

I have the following structure:

<div id="foo">
...
    <span name="bar">Lorem Ipsum</span>
    <span name="zzz">dolor sit amet</span>
...
</div>

Given that I know the id of the <div> , how can I change the text of the <span> tag with attribute name=bar ?. Note that there might be several/different <div> tags with one <span name="bar"> each.

I have tried:

$("#foo").find("span[@name='bar']").text("Phasellus congue arcu turpis");

What is missing/wrong?

span[@name='bar'] is not a valid jQuery selector. You need span[name='bar'] (remove the @ ).

// Notice the simplified/combined selector below
$("#foo span[name='bar']").text("Phasellus congue arcu turpis");

If you have several div 's that require modification, you should be using a class selector (demonstrated in the fiddle below).

// jQuery class selector
$(".divsWithSpans span[name='bar']").text("Phasellus congue arcu turpis");

Here's a quick reference for selectors , and a working fiddle to play with.


 // ID selector $("#foo span[name='bar']").text("Phasellus congue arcu turddpis"); // Class selector $(".divsWithSpans span[name='bar']").text("Phasellus congue arcu turpis"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!–– ID Selector ––> <div id="foo"> <span name="bar"></span> </div> <!–– Class selector ––> <div class="divsWithSpans"> <span name="bar"></span> </div> <div class="divsWithSpans"> <span name="bar"></span> </div> <div class="divsWithSpans"> <span name="bar"></span> </div> <div class="divsWithSpans"> <span name="bar"></span> </div> <div class="divsWithSpans"> <span name="bar"></span> </div> 

As you said, several div with that span[name='bar'] .

  • Remove the @ in your selector.

 $("div").find("span[name='bar']").text("Phasellus congue arcu turpis"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="foo"> <span name="bar">Lorem Ipsum</span><br> <span name="zzz">dolor sit amet</span> </div> <div id="nofoo"> <span name="bar">Lorem Ipsum</span><br> <span name="zzz">dolor sit amet</span> </div> 

Hope it helps!

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