Reputation: 528
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?
Upvotes: 0
Views: 1391
Reputation: 3522
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.
Upvotes: 0
Reputation: 1001
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";
Upvotes: 4
Reputation: 44871
#something : nth-child(1) {
float: left;
}
#something : nth-child(2) {
float: left;
}
#something : nth-child(3) {
float: left;
}
Might do what you want...
Upvotes: 3
Reputation: 4042
var elems = document.getElementById("something").getElementsByTagName("li");
for (var i = 0; i < 3; i++) {
elems[i].style.float = "left;
}
Upvotes: 1
Reputation: 6920
you can use getElementByTagName function
eg:
document.getElementsByTagName("li");
Upvotes: 0