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
  • 25,161
  • 11
  • 89
  • 121
Alien Xu
  • 193
  • 2
  • 3
  • 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
  • 66,980
  • 10
  • 72
  • 94
  • 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
  • 23,369
  • 6
  • 54
  • 74
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
  • 732
  • 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
  • 25,161
  • 11
  • 89
  • 121
0

Try :

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

Working Fiddle

4b0
  • 21,981
  • 30
  • 95
  • 142