0

I want to set float values for the first three li present in my HTML using javascript. I have named the parent ul as "something". Is it possible to set the float attribute for these li without naming them?

1
  • could you please paste in your code? Commented Aug 4, 2011 at 6:29

5 Answers 5

4

Sure, you can find the unnamed li elements in pure javascript using this snippet:

var children = document.getElementById('something').getElementsByTagName('li');

Where something is the name of the parent.

Then you access the first three children as usual

children[0].style.float = "left";
children[1].style.float = "left";
children[2].style.float = "left";
Sign up to request clarification or add additional context in comments.

Comments

3
#something : nth-child(1) {
    float: left;
}

#something : nth-child(2) {
    float: left;        
}

#something : nth-child(3) {
    float: left;        
}

Might do what you want...

3 Comments

You beat me to it by 31s so you can have my jsfiddle if you want it: jsfiddle.net/ambiguous/h7aVK
+1 for using CSS, but the OP said "named 'something'" so # selector might not be correct. The name attribute is not standard for UL elements.
I needed to do this during runtime, so thats why I wanted to use javascript.
1
var elems = document.getElementById("something").getElementsByTagName("li");
for (var i = 0; i < 3; i++) {
    elems[i].style.float = "left;
}

1 Comment

this will get every li on the page
0

you can use getElementByTagName function

eg:

document.getElementsByTagName("li");

Documentation

Comments

0

You can use .getElementsByName and .getElementsByTagName.

See:

<html>
<head>
<script>
  function f () {
    var objUl = document.getElementsByName("Test")[0];
    var lstLi = objUl.getElementsByTagName("li");
    for (var i=0; i < 3; i++) {
      lstLi[i].style.color = "red";
    }
  }
 </script>
</head>
<body>
<ul name="Test">
 <li> One </li>
 <li> Two </li>
 <li> Three </li>
 <li> Four </li>
</ul>
<input type="button" onclick="f()" value="Click me" />
</body>
</html>

I use style.color here for illustrative purposes. Obviously, you'd want to use style.float = "left" to float them left.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.