按类和ID获取元素内部元素 - JavaScript [英] Get element inside element by class and ID - JavaScript

查看:117
本文介绍了按类和ID获取元素内部元素 - JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,之前我曾涉猎过JavaScript,但我写的最有用的东西是CSS样式切换器。所以我对此有些新意。假设我有这样的HTML代码:

Alright, I've dabbled in JavaScript before, but the most useful thing I've written is a CSS style-switcher. So I'm somewhat new to this. Let's say I have HTML code like this:

<div id="foo">
    <div class="bar">
        Hello world!
    </div>
</div>

我如何更改Hello world!到再见世界! ?我知道document.getElementByClass和document.getElementById如何工作,但我想更具体。很抱歉,如果之前已经询问过。

How would I change "Hello world!" to "Goodbye world!" ? I know how document.getElementByClass and document.getElementById work, but I would like to get more specific. Sorry if this has been asked before.

推荐答案

那么,首先你需要选择具有<$ c $等功能的元素c> getElementById 。

Well, first you need to select the elements with a function like getElementById.

var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];

getElementById 只返回一个节点,但 getElementsByClassName 返回一个节点列表。因为只有一个元素具有该类名称(据我所知),你可以得到第一个元素(这就是 [0] 的用途 - 它是 - 就像一个数组)。

getElementById only returns one node, but getElementsByClassName returns a node list. 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).

然后,你可以用 .textContent 更改html。

Then, you can change the html with .textContent.

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>

这篇关于按类和ID获取元素内部元素 - JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆