[英]How to target elements in li with javascript
Here is a code of javascript for example i want to change the text in the span that is nested in li.这是一段javascript代码,例如我想更改嵌套在li中的跨度中的文本。 How do i use the DOM to target this elements ?我如何使用 DOM 来定位这些元素?
var body = document.getElementsByTagName('body')[0] body.style.fontFamily = "Arial"; var name = document.getElementsById('name'); var index = document.getElementsById('index'); var hometown = document.getElementsById('hometown'); name.innerHTML = "NAME"; index.innerHTML = "INDEX"; hometown.innerHTML = "HOMETOWN";
<h1>About Me</h1> <ul> <li>Name: <span id="name"></span> <li>Index: <span id="index"></span> <li>Hometown: <span id="hometown"></span> </ul>
<li>
for formatting reasons出于格式原因,请关闭<li>
var body = document.getElementsByTagName('body')[0] body.style.fontFamily = "Arial"; var nameSpan = document.getElementById('name'); // either change the var or the ID - I suggest the ID since name is used in several places like window.name etc var index = document.getElementById('index'); var hometown = document.getElementById('hometown'); nameSpan.innerHTML = "NAME"; index.innerHTML = "INDEX"; hometown.innerHTML = "HOMETOWN";
<h1>About Me</h1> <ul> <li>Name: <span id="name"></span></li> <li>Index: <span id="index"></span></li> <li>Hometown: <span id="hometown"></span></li> </ul>
Firsts of all you have a typo in getElementsById
, it should be getElementById
.首先,您在getElementsById
有一个错字,它应该是getElementById
。 And second, you should +=
the HTML not just =
, cause it deletes the text in your HTML and replace it with the value you set in JavaScript.其次,您应该+=
HTML 而不仅仅是=
,因为它会删除 HTML 中的文本并将其替换为您在 JavaScript 中设置的值。 And the last thing, it's better to give an id for <li>
, it's more sufficient than making span, I think.最后一件事,最好为<li>
提供一个 id ,我认为这比制作 span 更足够。
This is te fixed HTML and JS:这是固定的 HTML 和 JS:
document.getElementById("name").innerHTML += "anything"; document.getElementById("index").innerHTML += "anything"; document.getElementById("hometown").innerHTML += "anything";
<h1>About Me</h1> <ul> <li id="name">Name: <li id="index">Index: <li id="hometown">Hometown: </ul>
you have typos in the script as getElementById
not getElementsById
您在脚本中有拼写错误,因为getElementById
而不是getElementsById
Also HTML Have some tag issue还有 HTML 有一些标签问题
Try this尝试这个
<ul>
<li>Name: <span id="name"></span></li>
<li>Index: <span id="index"></span></li>
<li>Hometown: <span id="hometown"></span></li>
</ul>
var body = document.getElementsByTagName('body')[0]
body.style.fontFamily = "Arial";
var name = document.getElementById('name');
var index = document.getElementById('index');
var hometown = document.getElementById('hometown');
name.innerHTML = "NAME";
index.innerHTML = "INDEX";
hometown.innerHTML = "HOMETOWN";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.