Hide element if it contains specific text - javascript

I have the following code on my ecommerce website.
I would like to search to check whether it contains "0.00"
If it does contain "0.00" I would like to hide the parent div containing the price
This is because we want the product to appear online but even though it cannot be purchased, the price is still displayed, so we don't want people to be confused if they see the price as £0.00.
<div class="ct_pd_item_price ct_pd_item_value">
<span itemprop="price">
<span class="ct_currencyCode">GBP</span>
<span class="ct_currencySymbol">£</span>0.00</span>
</div>
Is this possible using some form of javascript?

If you can't change your HTML, it's a little tedious because the text must be cleand from the currencyCode and currencySymbol. A way to do this is to clone the div and then take the text :
$(".ct_pd_item_price.ct_pd_item_value").filter(function(){
return $(this).clone().find('.ct_currencyCode, .ct_currencySymbol').remove().end().text().trim()=="0.00"
}).hide()
Demonstration
Of course a cleaner HTML, maybe with the value in a data attribute, would be easier to deal with.

Another way with a regular expression
$('[itemprop="price"]').each(
function() {
var elem = $(this);
if (elem.text().match(/[^\d]0\.00/)) {
elem.closest(".ct_pd_item_price.ct_pd_item_value").hide();
}
}
);
Pulls out the text and it will be £0.00 so match that the price is not [anynumber]0.00

Related

Accessibility JS Function "Role" Attribute

I'm trying to write a JS function that would give empty heading elements (h1, and h2...)a “role” attribute value of “presentation”.
This is my first time working with accessibility in my projects and would love some help!
If they're empty, do they need to be there at all? The most correct thing is just to remove them.
However, you can use document.querySelectorAll() to get all the headings, then look inside each one to see whether they are empty. If they are, you can set the role attribute. The following code is very quick and dirty, but will get you some of the way.
var headings = document.querySelectorAll("h1,h2,h3,h4,h5,h6");
// iterate through each heading
Array.prototype.forEach.call (headings, function (node) {
// remove all white space
var theTextContent = node.textContent.replace(/\s/g,'');
// see if there's anything left in the string
if (theTextContent.length < 1) {
// node contains no visible text, mark it as presentation
node.setAttribute("role", "presentation");
}
} );
BUT this is a risky heuristic. Some headings might not contain text nodes, yet still appear as text on screen (e.g. they may have a background image in CSS representing a text in bitmap form). Instead of adding role="presentation" to these, you absolutely should add an aria-label with the correct heading text, otherwise you'll be violating at least two WCAG success criteria. ("Images of Text" and "Headings and Labels").
If you were using style attributes it might look something like this:
<h1 aria-label="welcome" style="background:url(welcome.png);"></h1>

Format text as user inputs in a contenteditable div

I'm attempting to make a page that allows users to input text and it will automatically format the input -- as in a screenplay format (similar to Amazon's StoryWriter).
So far I can check for text with ":contains('example text')" and add/remove classes to it. The problem is that all of the following p tags inherit that class.
My solution so far is to use .next() to remove the class I added, but that is limited since there might be need for a line break in the script (in dialogue for instance) and that will remove the dialogue class.
$('.content').on('input', function() {
$("p.input:contains('INT.')").addClass("high").next(".input").removeClass("high");
$("p.input:contains('EXT.')").addClass("high").next(".input").removeClass("high");
});
I can't get || to work in the :contains parameter either, but that's the least of my issues.
I have a JS fiddle
I've worked on this for a while now, and if I could change only the node that contains the text (INT. or EXT. in this example) and leaves the rest alone that would work and I could apply it to the rest of the script.
Any help would be appreciated, I'm new to the stackoverflow so thank you.
See the comments in the code below for an explanation of what's going on.
Fiddle Example
JQuery
var main = function(){
var content = $('.content');
content.on('input', function() {
$("p.input").each(function() {
//Get the html content for the current p input.
var text = $(this).html();
//indexOf will return a positive value if "INT." or "EXT." exists in the html
if (text.indexOf('INT.') !== -1 || text.indexOf('EXT.') !== -1) {
$(this).addClass('high');
}
//You could include additional "if else" blocks to check and apply different conditions
else { //The required text does not exist, so remove the class for the current input
$(this).removeClass('high');
}
});
});
};//main close
$(document).ready(main);

Create a region on HTML with changing values

I am a beginner in HTML and I want to create a region on a HTML page where the values keep on changing. (For example, if the region showed "56" (integer) before, after pressing of some specific button on the page by the user, the value may change, say "60" (integer) ).
Please note that this integer is to be supplied by external JavaScript.
Efforts I have put:
I have discovered one way of doing this by using the <canvas> tag, defining a region, and then writing on the region. I learnt how to write text on canvas from http://diveintohtml5.info/canvas.html#text
To write again, clear the canvas, by using canvas.width=canvas.width and then write the text again.
My question is, Is there any other (easier) method of doing this apart from the one being mentioned here?
Thank You.
You can normally do it with a div. Here I use the button click function. You can do it with your action. I have use jquery for doing this.
$('.click').click(function() {
var tempText = your_random_value;
// replace the contents of the div with the above text
$('#content-container').html(tempText);
});
You can edit the DOM (Document Object Model) directly with JavaScript (without jQuery).
JavaScript:
var number = 1;
function IncrementNumber() {
document.getElementById('num').innerText = number;
number++;
}
HTML:
<span id="num">0</span>
<input type='button' onclick='IncrementNumber()' value='+'/>
Here is a jsfiddle with an example http://jsfiddle.net/G638z/

Using javascript to pull specific page text, and then write to a span tag

I am currently trying to mark up my website product pages with product rating microdata for google SERP benefits.
The current cart software I am using does have a product rating system. It generates the following html related to the product's rating:
<span id="dnn_ctr783_ProductDetails_ctl02_lblAvgStars2">Average Rating: 5 Stars</span>
I am able to add the schema.org identifier to this span tag to produce the following:
<span id="dnn_ctr783_ProductDetails_ctl02_lblAvgStars2" itemprop="ratingValue">Average Rating: 5 Stars</span>
However, the value specified in the span tag is not valid with schema.org. They require that the "ratingValue" only contain a single digit to specify the rating. My span tag has a lot of additional text.
Somehow, I need to pull the number "5" from the generated rating span tag, and write it into another span tag which will have the proper value for the schema.org product markup.
Any ideas on how to accomplish this? Thanks!
Note that it's unlikely that search engines will execute any kind of javascript when crawling your site, so this technique would only work on regular browsers, but would have no effect in search engines.
Can you give more details on how this span is created and used?
This should get your value if you just want a single digit in a span with the 'itemprop' attribute.
$('[itemprop="ratingValue"]').text().match(/\d/g)
$('[itemprop="ratingValue"]').each(function() {
var txt = $(this).text(),
rating = txt.replace(/\D/g, '' );
// This will replace all the non-numeric instances
$('<span/>', {
'class' : 'newRatingValue',
text : rating
}).appendTo('#div1');
// Append this to a new span and remove the current span
$(this).remove();
});
Check Fiddle

Grab a single digit out of a big mess of html

I am grabbing a div from the document with :
var myTotal = window.document.getElementById('status').innerHTML;
which returns a big mess of HTML
<div id="foo">
<a href="bar" onclick='_gaq.push(["_trackEvent", "The", "Total",])'>
<img src="foo.gif" alt="foo" height="22px;/" width="15px;"></a>
</div>
<a href="bar" onclick='_gaq.push(["_trackEvent", "The", "Total",])'>
MY TOTAL:
<span style="font-size: 12px; color: #F3A428; font-weight:normal;"> 8 item(s) </span>
</a>
Can one of you expression wizards please show me how I can grab just the number in the span, in this example an 8 ?
Can you give the span an id and reference it directly?
If not, then this regex should return the number in the span: /<span[^>]+>\s*(\d+)/
I'm assuming that there is only ever one span in the div.
This should help you
var myTotal = window.document.getElementById('status').getElementsByTagName('span')[0].innerHTML
myTotal = myTotal.replace(/(^\d+)(.+$)/i,'$1');
In jQuery, without even getting the inner HTML it would be this:
var items = $("#status span").first().text();
items = parseInt(items, 10);
alert(items); // 8
If you control the HTML, it would be advisable to put a unique ID on the span containing the result and then it's easier to retrieve and not dependent upon the structure around it or better yet, have it output into the page as a JS variable that you can just directly read and not have to deal with the presentation.
Seen in a jsFiddle here: http://jsfiddle.net/jfriend00/UqcxS/
You can also try, just using innerText
window.document.getElementById('status').innerText.replace(/[^0-9]/gi, '');
http://jsfiddle.net/X9ffE/
Use jQuery instead, it has a lot of functions that can help you find specific elements in your page. Also, you may want to add identification for your elements like class and id.

Categories

Resources