0

When a particular page loads, these are the state of the <li> elements:

<li class="li1 frame3" style="display: list-item; opacity: 0.3; left: 0px; top: 20px; z-index: 2;"></li>
<li class="li2 frame4" style="display: list-item; opacity: 0.3; left: 151px; top: 0px; z-index: 2;"></li>
<li class="li3 frame5" style="display: list-item; opacity: 0.3; left: 0px; top: 0px; z-index: 2;"></li>

At any point, there is only one <li> having the left: 0px; top: 0px. I want to add a class (say, .dummy ) to the <li> element that has this property using javascript.

I'm a newbie in Javascript. I tried add ign this:

$("li").addClass("dummy");

But I couldn't figure out the required if statement.

6
  • 2
    I'm sure you do. What, exactly, have you tried? Commented Jan 27, 2013 at 10:24
  • loop thru all <li> elements and compare element.style.left and element.style.top. I am afraid there is no easier way to do it Commented Jan 27, 2013 at 10:24
  • @JackManey: Please see the edits, and please remove the down-vote. Commented Jan 27, 2013 at 10:32
  • @xan - I'll downvote whenever I please. What do you mean "required if statement"? If you want to add a class to an element, then add a class to an element. Commented Jan 27, 2013 at 10:36
  • @JackManey: I also need the condition, that when a particular <li> element is found to have the property left:0px; top:0px apply the addClass to that <li> element only. I was unable to figure out that condition; how to check for the inline style. Commented Jan 27, 2013 at 10:39

3 Answers 3

2

If you are asking how to add a class name to a DOM element, it goes something like this:

var liElements = document.getElementsByTagName("li");
for (var i = 0; i < liElements.length; i++) {
  var liElement = liElements[i];
  if (liElement.style.top == "0px" && liElement.style.left == "0px") {
    liElement.className += " dummy"; //Add the class name. Notice that the property is not called 'class'
  }
}

Edit: Added code to loop through li elements...

Sign up to request clarification or add additional context in comments.

Comments

1
div.classList.add("anotherclass");

details: https://developer.mozilla.org/en-US/docs/DOM/element.classList

1 Comment

Perhaps you should put the support info for classList here. Don't get me wrong, I think classList is great, I use it a lot myself, but I'm aware of the fact that I'll need an alternative if I have to support IE9/ IE Mobile.
-2

i'm not sure what you want to do.

but to add a class with jquery you can use this:

$(selector).addClass(classname,function(index,oldclass))

You can read about it here: http://www.w3schools.com/jquery/html_addclass.asp

1 Comment

This is not a jQuery question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.