SearchForKnowledge
SearchForKnowledge

Reputation: 3751

How to get only part of a string from a DIV using JS

<div class="faddress">
    1 myroad valley<br>beverly, VT&nbsp;54803-0989<br>(435) 425-9090 <br><br>
    <a href="someline.html" target="_blank" title="RBP">RBP</a>
    <br><span>(435) 425-9090 </span>
    <div class="mE">1 myroad valley&nbsp;beverly, VT&nbsp;54803-0989</div>
</div>

I am trying to get only 1 myroad valley and I used the following JS:

var vAdd = $(".mE").text();
var vArr = vAdd.split("&nbsp;");
console.log(vArr[0]);

I keep getting the following: 1 myroad valley beverly, VT 54803-0989

How can I modify the code to get the desired result.

Upvotes: 2

Views: 120

Answers (3)

Shijin TR
Shijin TR

Reputation: 7756

Here is a javascript only solution,No need jQuery

var vAdd = document.getElementsByClassName('mE')[0].innerHTML;
var vArr = vAdd.split("&nbsp;");
console.log(vArr[0]);

DEMO

Upvotes: 1

FatalError
FatalError

Reputation: 550

Use .html instead of .text:

var vAdd = $(".mE").html();
var vArr = vAdd.split("&nbsp;");
alert(vArr[0]);

.text function get only text and ignore HTML. That's why .text not getting &nbsp; and you are getting full text.

DEMO.

Upvotes: 5

Ram
Ram

Reputation: 144659

Use the html method instead of the text and your code will work.

> $(".mE").html();
> "1 myroad valley&nbsp;beverly, VT&nbsp;54803-0989"
> $(".mE").text();
> "1 myroad valley beverly, VT 54803-0989"

Upvotes: 5

Related Questions