Harish
Harish

Reputation: 528

How can I access unnamed elements from an HTML using javascript?

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

Answers (5)

MGwynne
MGwynne

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

Dan Mazzini
Dan Mazzini

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

Tom
Tom

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

Clueless
Clueless

Reputation: 4042

var elems = document.getElementById("something").getElementsByTagName("li");
for (var i = 0; i < 3; i++) {
    elems[i].style.float = "left;
}

Upvotes: 1

nidhin
nidhin

Reputation: 6920

you can use getElementByTagName function

eg:

document.getElementsByTagName("li");

Documentation

Upvotes: 0

Related Questions