View Full Version : is this script opener right? getting element class

09-09-2011, 07:24 PM
The script inside my opening if statement is working, but is the rest of this written right? I'm just want my script to run after it makes sure that a div class named single-journal-entry-wrapper is on the page.

function doit() {

for ( var x = 0; x < div.length; x++ )
var div = div[x];
if ( div.className.indexOf("single-journal-entry-wrapper") >= 0 )
{ do somethang!}


Old Pedant
09-09-2011, 07:53 PM
Looks right to me.

You might want to add break; at the end of your "do domehting" code, else if there is more than one <div> with that class name the "do something" code will execute once for each such <div>. The break; says "exit the surrounding for loop".

09-09-2011, 08:11 PM
hmmm... the break; didn't make a difference. I did find a jquery solution that works:

if($('div').hasClass('single-journal-entry-wrapper')) {do something}

But as I learn more, that has me wondering what the problems with using jquery are. I know it's obviously cheating me out of learning to code properly. But other than that?

Old Pedant
09-09-2011, 09:17 PM
Teach me not to read carefully!

You omitted a very important variable assignment and then misused a variable.

function doit()
// you MUST assign the collection of <div>s to a variable!
var divs = document.getElementsByTagName("div");
// you must search *IN* that collection!
for ( var x = 0; x < divs.length; x++ )
// and must get one member of that collection:
var div = divs[x];
if ( div.className.indexOf("single-journal-entry-wrapper") >= 0 )
alert("Found this: " + div.innerHTML );
// try un-commenting next line to see the difference
// break;
window.onload = doit;
<div class="whompit">
should not find this
<div class="whompit single-journal-entry-wrapper">
should find this first
<div class="single-journal-entry-wrapper">
should ALSO find this if you omit the break

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum