It appears you have not yet registered with DEVPPL. To register please click here... (it's fast, easy and free!)

Forum

Log In Sponsors
Board index Programming JavaScript Forum

Removing <p> elements with a certain className

Removing <p> elements with a certain className

Postby iwasfirst on Wed Dec 10, 2008 10:53 pm

Hi,

I'm just getting into the world of Javascript and is faced with this following problem:
How to filter out and hide/remove only those <p> elements that I've given a certain className with unobtrusive javascript.

Is there anyone out there that can display an example of how this is done??

Please - I would be eternally greatful!!
iwasfirst
 
Posts: 0
Joined: Wed Dec 10, 2008 10:51 pm

Re: Removing <p> elements with a certain className

Postby rangana on Thu Dec 11, 2008 1:42 am

First, you should get a copy of all those elements via DOM. A basic example:
Code: Select all
<script type="text/javascript">
var ray=
{
getClass:function(clsNme)
   {
   var clsArr = []; // Initialize an empty array
   var myclass = new RegExp('\\b'+clsNme+'\\b'); // Do some regular expression matchin
   var el = document.getElementsByTagName('*'); // Get all elements
   for (var i = 0 ; i < el.length ; i++ )
      {
      if (myclass.test(el[i].className)) // If the class name matches of the passed argument
         clsArr.push(el[i]); // Add the element in our array
      } // End of the for loop
   return clsArr; // Return the array to the callee
   }, // End of func
toggle:function(cls)
   {
   var el = this.getClass(cls);
   for (var i = 0; i < el.length ; i++)
      el[i].style.display = el[i].style.display!='none'?'none':'';
   }
}
</script>
<a href="#" onclick="ray.toggle('myclass'); return false;">Show/Hide</a>
<br><br>
<p class="myclass">
Paragraph element with a class name of "myclass"
</p>
<p class="myclass another_class">
Paragraph element with multiple class names and "myclass" is one of them
</p>
<p class="notmyclass">
Paragraph element with a class name of "notmyclass"
</p>
<span>Span element with no class name</span><br>
<span class="myclass">Span element with no "myclass" class name</span>


If you want to get an element via its className, you can use the getClass method on ray object from the above script. A sample call of the method would be:
Code: Select all
<input type="button" value="GetClass" onclick="alert('There are '+ray.getClass('myclass').length+' elements with that className');">


Always remember that the getClass method returns an array. You can take advantage on that.

Hope that helps.
User avatar
rangana
500+ Club
 
Posts: 935
Joined: Wed Feb 27, 2008 5:14 am
Location: Cebu City Philippines


Who is online

Users browsing this forum: No registered users and 6 guests