Hiding Hiding - 1 year ago 54
jQuery Question

Jquery next() not working on span

I have html that looks like this:

<span class="subHeader">Line of Business: </span>
<br>
<span class="sk-hits-grid-hit__state" style="margin: 5px; text-align: center;">General Liability,Workers Comp,</span>


I want to grab "General Liability,Workers Comp," as a string.

With jQuery I can get the correct subHeader by

$('.subHeader').filter(function () {
return $(this).text() === "Line of Business";
})


(I have other subHeaders so I have to check the text). I want to grab the sibling span element. I have tried both sibling() and next(), neither of which are returning anything. Any ideas?

Answer Source

It's .siblings() and this will get the span you mentioned

$('#subHeader').siblings('span.sk-hits-grid-hit__state').text()

Ex:

console.log($('#subHeader').siblings('span.sk-hits-grid-hit__state').text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="subHeader">Line of Business: </span>
<br>
<span class="sk-hits-grid-hit__state" style="margin: 5px; text-align: center;">General Liability,Workers Comp,</span>

Or $('#subHeader').next().next().text() (two nexts due to the <br>)

console.log($('#subHeader').next().next().text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="subHeader">Line of Business: </span>
<br>
<span class="sk-hits-grid-hit__state" style="margin: 5px; text-align: center;">General Liability,Workers Comp,</span>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download