Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

javascript - 通过类和ID获取元素内部的元素-JavaScript(Get element inside element by class and ID - JavaScript)

Alright, I've dabbled in JavaScript before, but the most useful thing I've written is a CSS style-switcher.(好的,我以前涉猎过JavaScript,但是我写的最有用的东西是CSS样式切换器。)

So I'm somewhat new to this.(所以我对此有些陌生。) Let's say I have HTML code like this:(假设我有这样的HTML代码:) <div id="foo"> <div class="bar"> Hello world! </div> </div> How would I change "Hello world!"(我将如何更改“ Hello world!”) to "Goodbye world!"(向“再见的世界!”) ?(?) I know how document.getElementByClass and document.getElementById work, but I would like to get more specific.(我知道document.getElementByClass和document.getElementById的工作方式,但我想更具体一点。) Sorry if this has been asked before.(抱歉,以前是否有人问过。)   ask by Tanner Babcock translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, first you need to select the elements with a function like getElementById .(好吧,首先,您需要使用诸如getElementById类的函数来选择元素。)

var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0]; getElementById only returns one node, but getElementsByClassName returns a node list.(getElementById仅返回一个节点,但是getElementsByClassName返回一个节点列表。) Since there is only one element with that class name (as far as I can tell), you can just get the first one (that's what the [0] is for—it's just like an array).(由于只有一个具有该类名称的元素(据我所知),因此您可以获取第一个元素(这就是[0]的含义-就像一个数组一样)。) Then, you can change the html with .textContent .(然后,您可以使用.textContent更改html。) targetDiv.textContent = "Goodbye world!"; var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0]; targetDiv.textContent = "Goodbye world!"; <div id="foo"> <div class="bar"> Hello world! </div> </div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...