简体   繁体   English

如何使用javascript访问HTML中的未命名元素?

[英]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. 我想使用JavaScript为HTML中出现的前三个li设置float值。 I have named the parent ul as "something". 我已将父母ul命名为“某物”。 Is it possible to set the float attribute for these li without naming them? 是否可以为这些li设置float属性而无需命名它们?

Sure, you can find the unnamed li elements in pure javascript using this snippet: 当然,您可以使用以下代码段在纯JavaScript中找到未命名的li元素:

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 您可以使用getElementByTagName函数

eg: 例如:

document.getElementsByTagName("li");

Documentation 文献资料

You can use .getElementsByName and .getElementsByTagName . 您可以使用.getElementsByName.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. 我在这里使用style.color进行说明。 Obviously, you'd want to use style.float = "left" to float them left. 显然,您想使用style.float = "left"将它们向左浮动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM