2
<h1>
    <br>
    USA
    <br>
    <br>
    <p style="margin-top:13px;" class="glyphicon glyphicon-chevron-down"></p>
    <br>
    <br>
    Canada 
</h1>

Without changing the HTML above, how can I get the value of Canada with jQuery selector?

Shashank Agrawal
  • 23,503
  • 10
  • 80
  • 110
Alien Xu
  • 163
  • 2
  • 2
  • 12
  • Possible duplicate of [Get the text after span element using jquery](http://stackoverflow.com/questions/6925088/get-the-text-after-span-element-using-jquery) – Shashank Agrawal Jun 20 '16 at 10:22

5 Answers5

3

If you want to get the last text-node value, then try this

var h1 = document.querySelector("h1");
var childNodes = h1.childNodes;
console.log(childNodes[childNodes.length -1 ].nodeValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><br>USA<br><br><p style="margin-top:13px;" class="glyphicon glyphicon-chevron-down"></p><br><br>Canada </h1>

Equivalent jquery would be

var h1 = $("h1")[0];
gurvinder372
  • 64,240
  • 8
  • 67
  • 88
  • hey the jquery version return the h1 selctor not the value. – Alien Xu Jun 20 '16 at 10:33
  • @AlienXu yes, you need to add next two lines to it. I just demonstrated that getting `h1` with javasript and jquery, you still need to iterate their childNodes. Basically, jquery doesn't help you much with textnodes. – gurvinder372 Jun 20 '16 at 10:35
1

If the markup style is consistent -- not prone to change, you can use xpath.

https://developer.mozilla.org/en-US/docs/Web/XPath

Jeremy J Starcher
  • 22,523
  • 6
  • 52
  • 73
1

You can also do something like this:

var value = $('h1').contents().filter(function() {
    return this.nodeType == 3;
})[1];

Here i use nodeType == 3, which selects text nodes.

https://jsfiddle.net/54tw4nw0/

Jaapze
  • 712
  • 6
  • 15
1

Here you go:

var afterP;

var text = $('h1').contents().filter(function() {
    if (this.nodeName == "P") {
        afterP = true
    }

    return afterP && this.nodeType == 3;
}).text();

console.log(text);

Solution copied & enhanced from Get the text after span element using jquery

Community
  • 1
  • 1
Shashank Agrawal
  • 23,503
  • 10
  • 80
  • 110
0

Try :

var text = $("h1").html();
alert(text.substring(text.lastIndexOf("<br>") +4));

Working Fiddle

4b0
  • 20,627
  • 30
  • 92
  • 137