简体   繁体   English

如何在 jquery 中从祖父母到第一个孩子第一个孙子

[英]How can I traverse down from grandparent to first child first grandchild in jquery

I have markup like this,我有这样的标记,

 <div class="new-content">
    <div>
        <button><span class="fa fa-xxx"></span></button>
        <span>Some text here</span>
    </div>
    <div class="some-other-div">
        <div>some text</div>
    </div>
 </div>

I want to change the text of span tag <span>Some text here</span> using jquery.我想使用 jquery 更改 span 标签<span>Some text here</span>的文本。 I used $('.new-content').children('div').first().children('span').first().text(''some other text');我用$('.new-content').children('div').first().children('span').first().text(''some other text'); to change the text, but I'm worried about code efficiency.更改文本,但我担心代码效率。 If you know better way to do this, please answer.如果您知道更好的方法,请回答。

You can select using CSS instead of chaining jQuery like so:您可以 select 使用 CSS 而不是像这样链接 jQuery :

 jQuery(".new-content > div:first-child > span:first-of-type").text("Replace text");
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="new-content"> <div> <button><span class="fa fa-xxx"></span></button> <span>Some text here</span> </div> <div class="some-other-div"> <div>some text</div> </div> </div>

You can benefit from client selection query like this: $(".new-content>div:first>span")您可以从这样的客户端选择查询中受益: $(".new-content>div:first>span")

 var tsx = $(".new-content>div:first>span").text(); $("#resul").html(tsx);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="new-content"> <div> <button><span class="fa fa-xxx">Hello</span></button><br> <span>Some text here</span> </div> <div class="some-other-div"> mdmdmdm </div> </div> <div id="resul"> \sdff </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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