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.
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.
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));
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">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.