I have this code:
<span class="price-measure">
23,63 € / 1 m2
</span>
Now, I want to change "/ 1 m2" with "XYTEXT" but I don't know how.
I tried to use JS code below, but it's not working.
Thank you :-)
<script type="text/javascript">
$(document).ready(function () {
var elem = $( '.price-measure span:contains("/ 1 m2 ")' );
elem.text( elem.text().replace("/ 1 m2 ", "s DPH/m2") );
});
</script>
var str1 = "23,63 € / 1 m2";
var str2 = "/ 1 m2";
if(str1.indexOf(str2) != -1){
alert("23,63 € / 1 m2".slice(0,-(str1.indexOf(str2)))+ 'XYTEXT')
}
str2 is the selected text needs to be replaced. so I just remove that section from main string and concatenate a new string.
var price = document.getElementById('price-measure').innerHTML
document.getElementById('price-measure').innerHTML= price.replace('1 m2','s DPH/m2')
i think good way use id with js not className
<br/><br/><br/><br/>
<span id="price-measure">
23,63 € / 1 m2
</span>
<span>23,63 €</span>
<span class="price-measure">/ 1 m2</span>
<script type="text/javascript">
$(document).ready(function () {
var elem = $('.price-measure');
elem.html("s DPH/m2");
});
</script>
Without changing the html content:
<span class="price-measure">
23,63 € / 1 m2
</span>
<script>
$(document).ready(function () {
var text = $('.price-measure').text().replace("/ 1 m2", "s DPH/m2");
$('.price-measure').text(text);
});
</script>
Your selector was wrong. You were asking for a span inside of .price-measure, when what you really wanted was the elements price-measure that contained your text.
For good coding practices, I also moved your hard-coded values into variables so they didn't get duplicated.
(I also removed the extra space from the end of your search query to make things more robust.)
$(document).ready(function () {
var replace="/ 1 m2";
var replaceWith = "s DPH/m2";
var elem = $('.price-measure:contains("' + replace + '")');
// Make sure we have the element.
console.log(elem);
elem.text(elem.text().replace(replace, replaceWith));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="price-measure">
23,63 € / 1 m2
</span>
I don't know how do this using jQuery, but in pure JS, you can do:
const el = document.querySelector(/* your selector */)
el.innerText = el.innerText.replace("/ 1 m2 ", "s DPH/m2")
You can try innerHTML property combined with split.
Something like this:
var first_part = $('.price-measure').innerHTML.split("/")[0];
var second_part = $('.price-measure').innerHTML.split("/")[1];
$('.price-measure').innerHTML.split("/")[0].append('XYTEXT');
$(document).ready(function(){
var t = $("span.price-measure").text().replace("/ 1 m2", "REPLACEMENT");
$("span.price-measure").text(t);
});
https://jsfiddle.net/kr09pquz/10/
If you don't need to pre-filter the elements, just iterate over them and replace their content:
$(document).ready(function() {
var elements = $('.price-measure');
elements.each(function(index, element) {
element = $(element);
element.text(element.text().replace('/ 1 m2', 's DPH/m2'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="price-measure">
23,63 € / 1 m2
</span>
If you have lots of elements and you need to pre-filter them before replacing their content, use jQuery's .filter(...) method to check, whether the specific element has the replaceable text:
$(document).ready(function() {
var replacement = '/ 1 m2';
var elements = $('.price-measure').filter(function(index, element) {
return $(element).text().indexOf(replacement) > -1;
});
elements.each(function(index, element) {
element = $(element);
element.text(element.text().replace('/ 1 m2', 's DPH/m2'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="price-measure">
23,63 € / 1 m2
</span>
Related
I have this div
<div class="address"><p>Test User<br>I. zone<br>Test street<br>3<br>11012</p></div>
I can select this text like this in jQuery
var fulline = $("div.address>p").text();
or
var fulline = $("div.address>p").html();
My question is how can I split this line to get a String like this:
I. zone Test street 3 11012
You can use: fulline.split("<br>").slice(1).join(" ")
Demo
var fulline = $("div.address > p").html();
console.log(fulline.split("<br>").slice(1).join(" "))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="address">
<p>Test User<br>I. zone<br>Test street<br>3<br>11012</p>
</div>
Alternatively you can use shift and join
var html = document.querySelector( ".address p" ).innerHTML;
var tmpItems = html.split( "<br>" );
tmpItems.shift();
console.log( tmpItems.join(" ") );
Demo
var html = document.querySelector( ".address p" ).innerHTML;
var tmpItems = html.split( "<br>" );
tmpItems.shift();
console.log( tmpItems.join(" ") );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="address"><p>Test User<br>I. zone<br>Test street<br>3<br>11012</p></div>
You can use this. Read the comments to get better insight of what is going on.
//get the html content of <p>
var fulline = $("div.address>p").html();
//split it using <br> so that you get an array
var res = fulline.split("<br>");
//remove the first element that contain 'Test User'
res = res.slice(1);
//join the array element using a space
res= res.join(" ");
console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="address"><p>Test User<br>I. zone<br>Test street<br>3<br>11012</p></div>
I am using money.js, a plugin to convert currency and am setting the content of a div like so:
currentDiv.html("<div>" + currentPrice + "</div><div class='converted'> " + rate.toFixed(0) + "</div>");
I am trying to separate the number with commas after every three digits and have tried adding .toLocaleString to the line but couldn't get it to work.
Have been looking on here all night for different solutions such as with regex etc. but haven't found anything yet...any ideas?
This is all the code:
<script src="https://raw.githubusercontent.com/openexchangerates/money.js/master/money.js"></script>
<script src="https://cdn.rawgit.com/openexchangerates/money.js/master/money.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="hello">
2300
</div>
<div class="hello">
52400
</div>
<script>
$(".hello").each(function() {
var currentDiv = $(this);
var currentPrice = currentDiv.text();
var demo = function(data) {
fx.rates = data.rates
var rate = fx(currentPrice).from("GBP").to("USD");
currentDiv.html("<div>"+currentPrice +"</div><div id='converted'> " +rate.toFixed(0)+"</div>");
}
$.getJSON("http://api.fixer.io/latest", demo);
});
</script>
As it is currency, It will have .## at the end of it right?
/^(?!0+\.00)(?=.{1,9}(\.|$))(?!0(?!\.))\d{1,3}(,\d{3})*(\.\d+)?$/
Below is some string, which should be serve as my HTML-Code.
I am trying from below string or HTML-Code separate the HTML-Tagname. After processing on the string the result should be something like as follows: =div=div=strong=em=p=b=p=p=h4=h1=span=.
Here is my HTML-Code in the variable "sTagName":
var sTagName = 'abc<div style="left:100px;" > some <div>MyText, <strong> hgz uz <em> Some text for flrdm <p><b>b, <p> <p><h4><h1><span id="MySpan">any text, ';
Here is my solution:
// Remove all attributes, e.g. <div style="left:100px;" > will be converted to <div>
sTagName = sTagName.replace(/<([a-zA-Z0-9]+).*?>.*?/g, '<$1>' );
// I add the "<>" at end of HTML-Code in order to remove the last useless string, I mean "Any text, "
sTagName = sTagName + "<>";
sTagName = sTagName.replace(/.*?<(.*?)>.*?/g,'=$1');
alert(sTagName);
The function alert(sTagName) delivers the expected result.
But I want improve my method referring to performance. E.g. I would like to build from two RegEx one RegEx, or something like that.
Any idea? Thanks in advance.
Use DOM:
var sTagName = 'abc<div style="left:100px;" > some <div>MyText, <strong> hgz uz <em> Some text for flrdm <p><b>b, <p> <p><h4><h1><span id="MySpan">any text, ';
tags = $("<div>").html(sTagName).find("*").map(function() {
return this.nodeName;
}).toArray();
document.write(tags);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can do that:
var sTagName = 'abc<div style="left:100px;" > some <div>MyText, <strong> hgz uz <em> Some text for flrdm <p><b>b, <p> <p><h4><h1><span id="MySpan">any text, ';
var arr = new Array;
var result;
var re = /<(\w+)/g;
while ((m = re.exec(sTagName)) !==null) {
arr.push(m[1]);
}
result = '=' + arr.join('=') + '=';
console.log(result);
Try
sTagName = $.map(sTagName.split(/[^<\w+]/), function(v, k) {
return /</.test(v) ? v.replace(/[a-z]+<|</g, "=") : null
}).join("").concat("=");
var sTagName = 'abc<div style="left:100px;" > some <div>MyText, <strong> hgz uz <em> Some text for flrdm <p><b>b, <p> <p><h4><h1><span id="MySpan">any text, ';
sTagName = $.map(sTagName.split(/[^<\w+]/), function(v, k) {
return /</.test(v) ? v.replace(/[a-z]+<|</g, "=") : null
}).join("").concat("=");
$("body").text(sTagName)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<(\w+)\s*[^>]*>|.(?=([^><]*<[^>]*>)*[^<>]*$)
Try this.Replace by $1.Later on append = to each result.
See demo.
http://regex101.com/r/qZ0uP0/2
I have 3 span tags that hold the price for each item and shipping. I need to add the three span tags together to come up with the total price using jQuery. Here is my code:
<div id="relative">
<div id="absolute">
Widget 1: <span id="widget_1_price">$99.99</span><br />
Widget 2: <span id="widget_2_price">$14.99</span><br />
Shipping Fee: <span id="shipping_price">$10.00</span><br />
<b>Total: <span id="total_price"></span></b>
</div>
</div>
I have tried several methods but none seem to work for me.
Loop through the elements and parse the text in them, and add them together:
var sum = 0;
$('#widget_1_price,#widget_2_price,#shipping_price').each(function(){
sum += parseFloat($(this).text().substr(1));
});
$('#total_price').text('$' + Math.round(sum * 100) / 100);
Demo: http://jsfiddle.net/QTMsE/
var val1 = parseFloat($("#widget_1_price").text().substring(1));
var val2 = parseFloat($("#widget_2_price").text().substring(1));
var shipping = parseFloat($("#shipping_price").text().substring(1));
var all = val1 + val2 + shipping;
$("#total_price").text("$"+all);
Try this.
Try this:
total = parseFloat($('#widget_1_price').text().slice(1))+
parseFloat($('#widget_2_price').text().slice(1))+
parseFloat($('#shipping_price').text().slice(1));
$('#total_price').text('$'+total);
I'm trying to add the content of each span along with the value in the title attribute.
<div id="group-wrap" class="group">
<span class="lbracket" title="&f">(</span>
<span class="grouptitle" title="&f"> Group </span>
<span class="rbracket" title="&f">) </span>
<span class="username" title="&f"> Username </span>
<span class="col" title="&f">:</span>
<span class="text" title="&f"> Helo There! </span>
</div>
Here is what I have so far:
var str = [];
$('#group-wrap span').each(function(){
str.push($(this).attr('title'));
});
alert(str.join(''));
});
http://jsfiddle.net/B9QeK/3/
The output is &f&f&f&f&f (the value of each title attribute), but the expected output has the value, plus the content that is in the span. The value of the attribute should be appended before the content.
&f(&fGroup&f)&fUsername: &f text
How can I get this result?
Looks like you are looking for
str.push( this.getAttribute('title'), this.textContent || this.text );
As for performance reasons, you should not re-create a jQuery object for every single iteration. Even better, don't use jQuery at all to receive those values.
JSFiddle
And by the way, you can make usage of jQuerys .map() to do it a bit more elegant:
jQuery(function($){
var str = $('#group-wrap span').map(function(){
return this.getAttribute('title') + this.textContent || this.text;
}).get();
alert(str.join(''));
});
JSFiddle
Reference: .map()
jQuery(function($){
var str = [];
$('#group-wrap span').each(function(){
str.push($(this).attr('title') + $(this).text());
});
alert(str.join(''));
});
Working JSFiddle
text:
Description: Get the combined text contents of each element in the set of matched elements, including their descendants.
docs
Just use the text method to get the text content of each span:
var str = [];
$('#group-wrap span').each(function(){
//Push value of title attribute and text content into array:
str.push($(this).attr('title') + $(this).text());
});
alert(str.join(''));
});
Your line
str.push($(this).attr('title'));
Should look like:
str.push($(this).attr('title') + $(this).text());
Although, this is making two identical calls $(this), so you might consider caching:
var $this = $(this)
str.push($this.attr('title') + $this.text());
var str = "";
$('#group-wrap span').each(function(){
str+=$(this).attr('title')+$(this).text();
});
alert(str);
});