Parsing horribly deprecated HTML with jQuery - javascript

I'm having some trouble understanding how to use nested selectors in jQuery. I'm parsing a list of classes from my university and I want it to let me know if a class I want is open. However, the website doesn't use css AT ALL, so the only way of identifying the class I want is open is to read the color attribute of the font tag.
Here's the block of HTML I'm trying to read
<TD><FONT FACE='Arial' SIZE='-1' COLOR='Black'>nameOfClass</TD>
Here's how am I'm trying to read it, and display an alert if the font tag attribute color of nameOfClass is "Black", which means its open. It's nasty but its the only way I can tell if the class is available or not.
function main() {
$(document).ready(function(){
if $("td").text()=="nameOfClass"
if $(this "font").attr("COLOR")=="Black" {
alert("It actually works!");
}
});
I never get an alert when I run this though. I'm pretty sure its my syntax, it's been a long while since I did any sort of coding so I might be making some stupid mistake.

You can use .children. But in order for your code to work, you have to iterate over all td elements, not just compare the text value of the first one:
$("td").each(function() {
if($(this).text() === 'nameOfClass' &&
$(this).children('font').attr('color') === 'Black') {
alert("It actually works!");
}
});
Otherwise, $("td").text()=="nameOfClass" only tests whether the text of the first td element in the page is "nameOfClass", which is certainly not what you want. You want to find all td element which contain that string.
You could do it much simpler if you'd directly select all font elements whose color attribute has the value "Black", with the attribute selector. Then you filter out the ones that don't contain the class name and count how many elements are left over. If none, then the class is not open.
var classIsOpen = $('font[color="Black"]').filter(function() {
return $(this).text() === 'nameOfClass';
}).length > 0;
You only need to do an exact comparison of the class name if it could occur as part of an other name, e.g. "Web" and "Advanced Web". If that's not the case, you can make the code even shorter, with the :contains selector:
var classIsOpen = $('font[color="Black"]:contains("nameOfClass")').length > 0;

Related

Read more opens 1st one all the time

I've a page with about 10 short articles.
Each of them as a "Read More" button which when pressed displays hidden text
The issues I have at the moment is when I press the "Read More" on any of the 10 button it shows the 1st articles hidden content and not the selected one.
I think I need to set a unique ID to each article.. and the read more button be linked to it.. But I don't know how to set it.
I looked at this but couldn't get it working how to give a div tag a unique id using javascript
var WidgetContentHideDisplay = {
init:function() {
if ($('#content-display-hide').size() == 0) return;
$('.triggerable').click(function(e){
var element_id = $(this).attr('rel');
var element = $('#'+element_id);
element.toggle();
if (element.is(':visible')) {
$('.readmore').hide();
} else {
$('.readmore').show();
}
return false;
});
}
}
var div = documentElemnt("div");
div.id = "div_" + new Date().gettime().toString;
$(document).ready(function(){ WidgetContentHideDisplay.init(); });
OP Edit: Sorry, the original code wasn't in caps. I kept getting errors when trying to post, so I copied the code into Dreamweaver and it made it all caps for some reason.
Instead of selecting the element to toggle with an ID (i.e. $('#'+ELEMENT_ID)) you could setup a class for your item and use the class selection (e.g. $('.DETAILED-ARTICLE)') to select the child (or the brother, etc. depending how you built the HTML page).
In theory each ID should point to a single element but each class can be put to as many elements as you want.
If you're getting errors, read the errors and see what they are. Off of a quick read of your code, here are a couple things I noticed that will probably cause issues:
"documentElemnt" is misspelled, which will render it useless. Also, documentElement is a read-only property, not a function like you're using it.
toString is a function, not a property, without the parentheses (.toString()) it isn't going to function like you want it to.
Run the code, look at the errors in the console, and fix them. That's where you start.

have element change appreance with only javascript and CSS

attempting to have my webpage be a bit more dynamic by having the background change on some elements when a checkbox is clicked. I am trying to do this via class change and a CSS sheet. I have the following which is kicking out an error that my onclick function ins not defined (in IE9). More importantly will the webpage update if I only change the class of the object which would have a different class in the CSS file. Whats a better alternative if this does not work?
my elemenet and function
UPDATE
I made updates to both my HTML and CSS file as suggested by many. I am still getting no change in my webpage but the console is claiming that my function called from the onclick event is not defined which is a bit odd since it is. Also does this type for scripting belong in the HTML or should I pull it out and put in a seperate file. I figured since it was creating elements it belongs in the main html. Is there a cleaner more compact way of accomplishing this and not making my home screen html huge?
<tr class= 'tr.notchosen'><td><input type='checkbox' onclick='handleClick(this.id)'/></td></tr>
function handleClick(cb) {
var currentColumn = cb.parentNode
var currentRow = currentColumn.parentNode
if (currentRow.className === "chosen")
{
currentRow.className = "notchosen";
}
else
{
currentRow.className = "chosen";
}
}
and my css file is the following
tr.chosen
{
background-color:rgba(255,223,0,0.75);
}
tr.notchosen
{
background-color:rgba(255,223,0,0);
}
There are a couple of things going on here. First, your css selector is not quite right. In fact, I would suggest making the class name just "chosen" or "not chosen" and then selecting tr elements with that class.
<tr class='notchosen'>
And then you can target it from css (which was probably the original intention)
tr.notchosen
{
background-color:rgba(255,223,0,0);
}
Further, although I would not suggest using inline javascript, using your example, you should pass this if you want to work with the element and not this.id which would pass a string.
onclick='handleClick(this)'
The last part would be to sync up your javascript with the class name change
if (currentRow.className == "chosen")
{
currentRow.className = "notchosen";
}
else
{
currentRow.className = "chosen";
}

Change the class of a hyperlink depending on its text

I'm trying to set up a web page that contains links to pages that have Disqus comments on them. There is specific guidance on adding a comment count to a link that Disqus provides, but it's not great. You are limited to using an <a> element, and it replaces the text of the hyperlink with new text.
So, if I create a hyperlink like this on my site:
linktext
after the page loads, it looks like this:
<a class="link-processed" href="http://mysite.com/posts/1234#disqus_thread">
(1 and 0)
</a>
(note that, by default, the replacement text would be "1 comment and 0 reactions" but I have modified the default text to return just the numbers, in brackets.)
When the text of the hyperlink is "(0 and 0)" I'd like to hide the link. When it is anything else, I'd like to replace the text of the link with an image link (little speech bubble or similar.)
I am thinking that the way to do this might be to use a couple of classes. I'll apply the first class (hidelink) by default, and use javascript to apply the second class to the <a> element.
However, now I'm stuck. Javascript is not my native domain. This seems like it should be a straightforward task, though?
What are your browser requirements? If you're using IE8+ (or most other browsers) you could use querySelectorAll or getElementsByClassName to get all processed links and then check if its text match your condition:
var elems = document.querySelectorAll('.link-processed');
for(var i = 0, size = elems.length; i < size; i++)
{
if(elems[i].innerText === "(0 and 0)")
{
//0 and 0. Do something
}
}
Alternatively, if you're using jQuery, you could simply select all elements that contain "0 and 0", using the pseudo class :contains:
$("a:contains('0 and 0')")

JQuery change color based of class based on HTML content

I am trying to use JQuery to get the inner html of a div (class box_bottom).
These div's are javascript generated, pulling from XML, therefore (dependant on the XML) there could be (and so I need to cater for) multiple occurrences, so cannot do this by ID. If the content is "notifications" then I want the color to be blue, and if the content is "VO" I want the color to be red
$.category = $('.box_bottom').innerHTML;
if ($.category == 'Notifications') {
$(".box_bottom").css("color", "blue");
}
if ($.category == 'VO')
{
$(".box_bottom").css("color", "red");
}
Chrome dev console is not showing any errors - I am unsure where I am going wrong.
Complete novice to JQuery so have just been googling syntax - so apologies if this is a super simple issue.
You can not access innerHTML property on jQuery object. You need to use html() instead of innerHTML
Change
$.category = $('.box_bottom').innerHTML;
To
$.category = $('.box_bottom').html();
OR
$.category = $('.box_bottom').text();
You may also need to use $.trim to avoid any extra space within text, and its better to use category instead of $.category as it defined category with $ jQuery object.
$.category = $.trim($('.box_bottom').text());
$.category = $('.box_bottom').text().trim();
if ($.category == 'Notifications') {
$(".box_bottom").css("color", "blue");
}
if ($.category == 'VO')
{
$(".box_bottom").css("color", "red");
}

How to get a DOM Element from a jQuery selector?

I'm having an impossibly hard time finding out to get the actual DOMElement from a jQuery selector.
Sample Code:
<input type="checkbox" id="bob" />
var checkbox = $("#bob").click(function() { //some code } )
and in another piece of code I'm trying to determine the checked value of the checkbox.
if ( checkbox.eq(0).SomeMethodToGetARealDomElement().checked )
//do something.
And please, I do not want to do:
if ( checkbox.eq(0).is(":checked"))
//do something
That gets me around the checkbox, but other times I've needed the real DOMElement.
You can access the raw DOM element with:
$("table").get(0);
or more simply:
$("table")[0];
There isn't actually a lot you need this for however (in my experience). Take your checkbox example:
$(":checkbox").click(function() {
if ($(this).is(":checked")) {
// do stuff
}
});
is more "jquery'ish" and (imho) more concise. What if you wanted to number them?
$(":checkbox").each(function(i, elem) {
$(elem).data("index", i);
});
$(":checkbox").click(function() {
if ($(this).is(":checked") && $(this).data("index") == 0) {
// do stuff
}
});
Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest.
Edit: seems I was wrong in assuming you could not get the element. As others have posted here, you can get it with:
$('#element').get(0);
I have verified this actually returns the DOM element that was matched.
I needed to get the element as a string.
jQuery("#bob").get(0).outerHTML;
Which will give you something like:
<input type="text" id="bob" value="hello world" />
...as a string rather than a DOM element.
If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.
But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.
UPDATE: Based on a comment:
Here is a post with a nice explanation: http://www.mail-archive.com/jquery-en#googlegroups.com/msg04461.html
$(this).attr("checked") ? $(this).val() : 0
This will return the value if it's checked, or 0 if it's not.
$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.

Categories