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?
-
could you please paste in your code?Side– Side2011-08-04 06:29:43 +00:00Commented Aug 4, 2011 at 6:29
Add a comment
|
5 Answers
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";
Comments
#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
mu is too short
You beat me to it by 31s so you can have my jsfiddle if you want it: jsfiddle.net/ambiguous/h7aVK
RobG
+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.
Harish
I needed to do this during runtime, so thats why I wanted to use javascript.
var elems = document.getElementById("something").getElementsByTagName("li");
for (var i = 0; i < 3; i++) {
elems[i].style.float = "left;
}
1 Comment
sym3tri
this will get every li on the page
Comments
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.