add what contains in element along with array - javascript

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);
});

Related

Get text between tags using javascript

I am trying to get prices from between span tags. I would like to have all prices in an array. I cant seem to get it to work, I am guessing my regex is incorrect.
I am looking for any span tags with the class 'amount', the tag has no other attributes set and only has one class. E.g. <span class="amount">£9.99</span>
var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
.map(function(val){
return val;
});
Output
[ '£9.99', '£100.00' ]
I am trying to get prices from between span tags. I would like to have all prices in an array. I cant seem to get it to work, I am guessing my regex is incorrect.
I am looking for any span tags with the class 'amount', the tag has no other attributes set and only has one class. E.g. <span class="amount">£9.99</span>
var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
.map(function(val){
return val;
});
Output
[ '£9.99', '£100.00' ]
* UPDATE *
Turns out it was an encoding with the ajax response resp.fragments['data'].
I was using regex as it is something I have not really used before in JS and thought I would have a play. I did look at many examples and after about 45 mins with no success I thought a fresh set of eyes would fix it.
#spaceman
Thanks for the helpful comment. Your one of those people if someone asked "Is there is a doctor in the house?", you would stand up and say "Sweet load there are loads of doctors out there".
While a regular expression could work for this, it might be easier to simply select the <span class='amount'> elements and map their innerHTML content to an array via the map() function:
// This would yield an array containing your values
var amounts = Array.prototype.slice
.call(document.querySelectorAll('span.amount'))
.map(function(a){ return a.innerHTML; });
You can see a working example of this demonstrated here.
Simplest method will be to add this to an invisible DOM object and then traverse it via DOM API
var text = '<span class="amount">£9.99</span><span class="amount">£9.99</span>'
//now append it to an DOM object
var wrapperDiv = "<div style='display:none' id='tmpDiv'>" + text + "</div>";
document.body.innerHTML += wrapperDiv;
var elements = document.querySelectorAll( "#tmpDiv amount" );
var output = Array.prototype.slice.call( elements ).map( function(val){
return val.innerText;
})
Another approach could be split the text by <span class="amount"> and get the value after first index
DEMO
var text = '<span class="amount">£9.99</span><span class="amount">£9.99</span>'
var output = [];
text.split('<span class="amount">').forEach( function(val, index) {
if (index > 0 )
{
output.push( val.replace( "</span>", "" ) );
}
});
document.body.innerHTML += JSON.stringify( output, 0, 4 );
You can use this instead.
var prices = document.getElementsByClassName('amount');
var price_array = [];
for (i= 0; i < prices.length; ++i) {
price_array.push(prices[i].innerHTML);
}
document.write(" | " + price_array);
<span class='amount'>£123</span>
<span class='amount'>£3</span>
<span class='amount'>£5</span>
<span class='amount'>£64</span>
You don't need to use regex or jQuery for this.

How to properly select a div with this?

I have a list of products, each one displayed whithin a div like this :
<div data-productSheetId="n" class="productSheet"></div>
My current selector is the following :
var productSheet = $('[data-productSheetId="' + $(this).data('productSheetId') + '"]');
I'm pretty sure i'm doing it wrong, how could i select it properly ?
You can use the .filter() method:
var productSheet = $("div.productSheet").filter(function() {
return $(this).data("productsheetid") == "n";
});
Update:
Thanks to #mplungjan. The data attributes should be all lowercase. Now, when the attribute has hyphens, the camel-case equivalent can be used to read the data:
//<div data-productsheetid="n" class="productSheet"></div>
//use:
.data('productsheetid')
//<div data-product-sheet-id="n" class="productSheet"></div>
//use either:
.data('product-sheet-id')
//or:
.data('productSheetId')
You likely meant to
have an all lowercase attribute
use the data-attribute to select the productsheet by its id
like this
<div id="xxx" class="productSheet"></div>
<div id="yyy" class="productSheet"></div>
<div id="zzz" class="productSheet"></div>
<button class="btn" type="button" data-productsheetid="xxx">Select XXX</button>
$(function() {
$(".btn").on("click",function() {
// get the id to access from the button's data attribute
var id = $(this).data("productsheetid"); // for readability
var productSheet = $("#"+id);
});
});
Just lowercase your key:
productSheet = $('[data-productSheetId="' + $(this).data('productsheetid') + '"]');
The camelcase key you are using (productSheetId) is used for attributes like
<div data-product-sheet-id="n" class="productSheet"></div>
var x = 5;
var productSheet = $('div[data-productSheetId =' + x + ']');
This is going to do trick. Just change the variable x when selecting.

Get specific value from a HTML output

I am getting the following result from a data source.
"<span class=\"highlight\">DSDT10</span><div>011XBY</div>"
The value in span and div could vary.
And I want only the value inside the span "DSDT10" in a separate variable.
What I have tried:
var data = '<span class=\"highlight\">DSDT10</span><div>011XBY</div>';
var formattedData = data.replace(/<\/?span[^>]*>/g, "");
$('#output').append(formattedData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
Expectation:
Retrieve only "DSDT10" from the data variable.
Any suggestion is appreciated. Thanks.
You just want to get the text within the span? You could modify your regex a bit and use a match..
var data = '<span class=\"highlight\">DSDT10</span><div>011XBY</div>';
var formattedData = data.match(/<span[^>]*>([^<]*)<\/span>/, "")[1];
But since you're using jquery you could also just do this:
var formattedData = $("<div>", {html: data}).find("span").text()
Only two lines of code:
_str = "<span class=\"highlight\">DSDT10</span><div>011XBY</div>";
_span = $(_str).filter('span').text();
It's enough only one line:
$('#output').html($('span').html());

JQuery find child element inner text and replace with IMG HTML

I need a little help with a Javascript function I am creating. In essence, I need to loop through a set of DIVs with class .DetailRow and find a child DIV's content (inner text). If this text is matched to a variable, then I need to replace this inner text with an IMG HTML statement.
BTW I am kinda new at this (4 months old!) so apologies if the issue is simple, but I have tried a few combos and I am stuck.
Here's the HTML:
<div class="DetailRow" style="display: ">..</div>
<div class="DetailRow" style="display: ">..</div>
<div class="DetailRow" style="display: ">
<div class="Label">Availability:</div>
<div class="Value">in stock + Free Shipping</div>
</div>
Example, if I find "in stock" in the LABEL inner text, I want to replace it with the value of the variable "instock" which is an IMG HTML statement. See my code attempt below.
<script type="text/javascript">
$(window).load(function(){
var instock = '<img src="https://linktoimgfolder/instock.gif" title="Product available, usually ships 24hrs to 48hrs after order receipt" style="margin-top:-3px;">';
var lowstock = '<img src="https://linktoimgfolder/lowstock.gif" title="Product stcok low, order today so you do not miss out">';
var nostock = '<img src="https://linktoimgfolder/outstock.gif" title="Product out of stock, could ship 1 to 2 weeks after order receipt">';
$('div.DetailRow')each(function(){
if (indexOf($(this).childNodes[1].innerHTML, "in stock") > 0) {
$(this).childNodes[2].innerHTML = "";
$(this).childNodes[2].innerHTML = instock;
} else if (indexOf($(this).childNodes[1].innerHTML, "low stock") > 0) {
$(this).childNodes[2].innerHTML = "";
$(this).childNodes[2].innerHTML = lowstock;
} else {
$(this).childNodes[2].innerHTML = "";
$(this).childNodes[2].innerHTML = nostock;
};
});
});
</script>​
By the way,m I cannot match text exactly as the text beyond the "+" will change from time to time, thus I am trying indexOf.
Many thanks in advance for your assistance!
M
Using the :contains selector
var stock = {'in stock': instock, 'low stock': lowstock, 'no stock': nostock};
Object.keys(stock).forEach(function(key) {
$('div.DetailRow div:contains(' + key + ')').html(stock[key]);
});
jsFiddle Demo
A pure jQuery solution:
$.each(stock, function(key, value) {
$('div.DetailRow div:contains(' + key + ')').html(value);
});
You have typo in this line $('div.DetailRow')each(function(){ and then you can use jQuery .text() and .html() to check value and update.
Try:
$('div.DetailRow').find("div").each(function(){
if($(this).text().indexOf("in stock")!=-1){
$(this).text("");
$(this).html(instock);
}else if($(this).text().indexOf("low stock")!=-1){
$(this).text("");
$(this).html(lowstock);
}else{
$(this).text("");
$(this).html(nostock);
}
});
DEMO FIDDLE
NOTE: Updated code to find div inside div.DetailsRow. Change it according to your requirement.

Add Html to Text without children element

I am very confused on how to get this work, did a lot of research online to help find a solution to this, but got nothing. Found this link here: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/ but still didnt help much
This is what I am trying to accomplish, the system is outputting text like this, I have no control over the html.
<div class="myclass">
Text 1
Text 2
Text 3
</div>`
but would like to use jquery to insert html around those text
For example:
<div class="myclass">
<span>Text 1 </span>
<span> Text 2 </span>
<span> Text 3</span>
</div>
any help is appreciated
thank you very much
$('.myclass').html(function(i, v){
return '<span>' + $.trim(v).split('\n').join('</span><span>') + '</span>';
});
http://jsfiddle.net/vDp6A/
There are other ways. This would satisfy the question.
$(function(){
stuff=$('.myclass').text().split("\n");
newhtml='';
$.each(stuff, function(i,o){
if (o!=''){
newhtml +='<span>' + o + '</span>'."\n";
}
});
$('.myclass').html(newhtml);
});
This should sort it:
var theDivs = document.getElementsByClassName('myclass');
for(var i in theDivs)
{
if(parseInt(i)==i)
{
var div = theDivs[i];
var text = div.innerHTML.split("\n");
for(var k in text)
{
var trimmed = text[k].replace(/^\s+|\s+$/,'');
if(trimmed != '') text[k] = '<span>'+trimmed+'</span>';
else text[k] = trimmed;
}
div.innerHTML = text.join("\n");
}
}

Categories