views:

172

answers:

3

i have this html:

<span class="price">
        $61.00
          <span class="detailFreeShipping">With Free Shipping</span>
    </span>

How to write a jquery selector which give me the price text only "$61.00"?

i want to make it generic as i can because may be in some cases there is no inner span, just the parent one.

A: 

I don't know jQuery, but just to pseudo-respond your question, you can do this by:

var elem = document.getElementById('yourid'); // or document.getElementsByTagName('span')[0];
var text = elem.innerHTML;
text = text.substr(0, (text.indexOf('<') > -1 ? text.indexOf('<') : text.length));
José Leal
+11  A: 

You can do this:

jQuery.fn.extend({
    textOnly: function() {
        // make a clone of this object so we are not changing the actual DOM
        var obj = $(this).clone();

        // remove all the children, i.e. any DOM objects
        obj.children().remove();

        // get the text value after all DOM elements are removed
        return obj.text();
    }
});

then you can call it like this

var price = $(".price").textOnly();

you will get the value you want.

Nick Berardi
just replace the "textOnly =" with "textOnly :"
Marwan Aouida
Thanks, I had it as a standalone function, but decided to extend it at the last min.
Nick Berardi
A: 

an attempt:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <script type="text/javascript" src="http://www.google.com/jsapi"&gt;&lt;/script&gt;
    <script type="text/javascript" charset="utf-8">
        google.load("jquery", "1.3");
    </script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function(){
            var white_out = $("span[class=price] :first-child").text();
            var all = $("span[class=price]").text();
            var price = all.replace(white_out, "");
            alert(price);
        });
    </script>
</head>
<body>
    <span class="price">
            $61.00
              <span class="detailFreeShipping">With Free Shipping</span>
        </span>
</body>
</html>

where the lines:

            var white_out = $("span[class=price] :first-child").text();
            var all = $("span[class=price]").text();
            var price = all.replace(white_out, "");

might do the work, for a single element.

The MYYN
what if the price is second in the element? the original author asked for it to be as generic as possible.
Nick Berardi
then it still works, because the first child get purged, as in your (more elegant) solution all the children elements get purged. the order does not matter, nor if there is a child element at all; i consider it "generic as possible" for the presented problem ...
The MYYN