Muhammad Saquib Shaikh
Muhammad Saquib Shaikh

Reputation: 298

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. I used $('.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.

Upvotes: 0

Views: 162

Answers (2)

Ahmed Hekal
Ahmed Hekal

Reputation: 478

You can benefit from client selection query like this : $(".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>

Upvotes: 1

Kalimah
Kalimah

Reputation: 11437

You can select using CSS instead of chaining jQuery like so:

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>

Upvotes: 4

Related Questions