Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Applying class to an HTML tag given an attribute/value

I am trying to apply styles to HTML tags dynamically by reading in the value of certain HTML attributes and applying a class name based on their values. For instance, if I have:

<p height="30">

I want to apply a class="h30" to that paragraph so that I can style it in my style sheet. I can't find any information on getting the value of an attribute that is not an id or class. Help?

like image 942
Joshua Avatar asked Aug 14 '26 10:08

Joshua


2 Answers

I would highly recommend using something like jquery where adding classes is trivial:

$("#someId").addClass("newClass");

so in your case:

$("p[height='30']").addClass("h30");

so this selects all paragraph tags where the height attribute is 30 and adds the class h30 to it.

like image 165
SeanDowney Avatar answered Aug 17 '26 00:08

SeanDowney


See: getAttribute(). Parameter is the name of the attribute (case insensitive). Return value is the value of the attribute (a string).

Be sure to see the Remarks in MSDN before dealing with IE...

like image 22
Shog9 Avatar answered Aug 17 '26 00:08

Shog9