2016-11-17 6 views
1

の残りの部分なしに、タグからテキストを取得します。私のHTMLは以下れるコンテンツ

私が試した:

var total = parseFloat($('.price').text()); 

感謝を。

+0

'は.text()あなたが' 'を得ることはありませんので、' htmlタグなしのテキストを取得します。https://jsfiddle.net/6m48w40s/ –

+0

@JonP:あなたは私が考えてすぐに私のテキストを読み出し。 – Bonito

答えて

1

$( "価格")

あなたが要素を指定する必要があり、コレクションまたは配列を返します。この場合は、JQuery eq機能を使用して指定することができます。 https://jsfiddle.net/ggderas/Ln7gd74n/3

+0

あなたのソリューションは最高のものになると思います。 – Bonito

+0

それでも、$( '。price')。eq(0).text() 'には0 $が返されます。https://jsfiddle.net/ab5ne0rh/ –

+0

気軽にhttps:// jsfiddle。net/ggderas/Ln7gd74n/ – ggderas

1

この

var price = $('.price').contents().map(function() { 
 
       if (this.nodeType == 3 && this.textContent.trim() != '') return Number(this.textContent); 
 
     }).get().join(); 
 

 
console.log(price);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 
 
<span class="price"> 
 
    0 
 
    <sup>$</sup> 
 
</span>
を試してください:あなたのHTMLが唯一のクラス 価格で一つの要素

youselfそれを試してみてくださいを持っているので、私は0(ゼロ)を使用してい

var total = parseFloat($('.price').eq(0).text()); 

+0

私はそれが美しいコードだと思っていますが、必要なものだけを取り除くのは難しいです。 – Bonito

+0

美しいコードとしてそれを言ってくれてありがとう – EaBangalore

0

innerHTMLを取得し、タグ内に何かを削除します。

var text = document.getElementsByClassName('price')[0].innerHTML.replace(/<.*>.*<\/.*?>/g, ''); 
 
console.log(text);
<body> 
 
    <span class="price"> 
 
    0 
 
    <sup>$</sup> 
 
</span> 
 
    <?body>

0

が1つのオブジェクトのみがpriceのクラスであり、あなたが子供である任意のテキストを無視することと仮定すると、ノード...

var total = parseFloat($('.price')[0].childNodes[0].nodeValue); 
 
console.log(total); 
 
console.log($('.price')[0].childNodes[0].nodeValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<span class="price"> 
 
    0<sup>$</sup> 
 
</span>

01これはまた、わずかな修正ではjQueryなく動作

var total = parseFloat(document.getElementsByClassName('price')[0].childNodes[0].nodeValue); 
1

あなたは以下の

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
\t <title></title> 
 
\t <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 
</head> 
 
<body> 
 

 
<span class="price"> 
 
    0 
 
    <sup>$</sup> 
 
</span> 
 

 

 
</body> 
 

 

 
<script type="text/javascript"> 
 
\t $(document).ready(function(){ 
 
\t \t var thePricewith_$ = $(".price").text(); // get the text 
 
\t \t var splitted = thePricewith_$.split("$"); // split it from dollar sign 
 

 
\t \t var onlyPrice = splitted[0]; // this gives the price text 
 
\t \t var dollarSign = splitted[1]; // this gives the dollar sign 
 
\t \t alert("price without dollar sign : "+ onlyPrice) // print only the price 
 

 
//additional, if you want to convert it to int and use it do it like this 
 
// var piceInt = parseInt(onlyPrice) 
 
// alert(piceInt+5) 
 

 

 
\t }); 
 

 
</script> 
 

 

 
</html>

  • のように分割することにより、容易にそれを得ることができ、また、あなたは杖に変換しますintにしてコメントのように使用します。これがあなたに役立つことを願っています。
関連する問題