开发者

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?


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";


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

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

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

Might do what you want...


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


you can use getElementByTagName function

eg:

document.getElementsByTagName("li");

Documentation


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜