使用 javascript 访问 HTML 元素而不使用 getElementById

发布于 2024-11-24 20:29:22 字数 484 浏览 3 评论 0原文

我是 JavaScript 新手。我创建了这个名为 colorme 的 div。我可以通过javascript成功地给它着色。现在假设我想更改

...

等的背景,我如何通过 Javascript 达到它? (没有jquery)。

就像 document.getElementById() 可以在 div 上工作一样,我到达了它。现在我不能继续为所有元素提供唯一的 id。我如何到达

等内部元素?

<div id="colorme">
  <p>Blah Vblah Blah Content</p>
  <span>Blah Vblah Blah Content</span>
</div>

I'm new to javascript. I created this div called colorme. I can successfully color it via javascript. Now assuming i want to change the background of <p>...</p>, or <span>,etc how do i reach it via Javascript? (no jquery).

Like document.getElementById() would work on the div and i reach it. Now i cannot keep giving unique id's to all the elements. How do i reach the inner elements like <p> or <span>, etc?

<div id="colorme">
  <p>Blah Vblah Blah Content</p>
  <span>Blah Vblah Blah Content</span>
</div>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

总以为 2024-12-01 20:29:22

您可以使用找到的元素作为 getElementsByTagName 的上下文。

var colorme = document.getElementById('colorme'),
    spans = colorme.getElementsByTagName('span');

请注意,spans 是一个 NodeList(类似于数组),包含 colorme 中的所有 span 元素。如果您想要第一个(实际上,代码示例中的唯一一个),请使用 spans[0]

You can use the element that you've found as a context for getElementsByTagName.

var colorme = document.getElementById('colorme'),
    spans = colorme.getElementsByTagName('span');

Note that spans is a NodeList -- similar to an array -- containing all the span elements within colorme. If you want the first one (indeed, the only one in your code sample), use spans[0].

巷子口的你 2024-12-01 20:29:22

您应该查看标准 javascript 中提供的许多 DOM 遍历函数。

教程: http://www.quirksmode.org/dom/intro.html

参考: http://reference.sitepoint.com/javascript/Node

http://reference.sitepoint.com/javascript/Element

You should check out the many DOM traversal functions provided in standard javascript.

Tutorial: http://www.quirksmode.org/dom/intro.html

Reference: http://reference.sitepoint.com/javascript/Node

and http://reference.sitepoint.com/javascript/Element

心欲静而疯不止 2024-12-01 20:29:22

这里有三种方法:

  1. 如果你只关心像样的浏览器,document.querySelector(返回第一个匹配的节点)和document.querySelectorAll(返回一个NodeList) -例如 document.querySelector('#colorme p')

  2. HTMLElement.getElementsByTagName()(返回 NodeList) - 例如 document.getElementById('colorme').getElementsByTagName('p')[0]

  3. HTMLElement.children 等 - document.getElementById(' colorme').children[0].firstChild 可能是一个文本节点,有很多有趣的 DOM 内容可以进入其中,链接到的 quirksmode DOM 介绍很好东西)。

Here are three ways:

  1. If you only care about decent browsers, document.querySelector (returns the first matching node) and document.querySelectorAll (returns a NodeList) - e.g. document.querySelector('#colorme p').

  2. HTMLElement.getElementsByTagName() (returns a NodeList) - e.g. document.getElementById('colorme').getElementsByTagName('p')[0]

  3. HTMLElement.children, etc. - document.getElementById('colorme').children[0] (.firstChild will probably be a text node, lots of fun DOM stuff to get into there, the quirksmode DOM intro linked to is good stuff).

影子的影子 2024-12-01 20:29:22

尽管答案确实为这种特定情况提供了很好的方法......

您面临的问题称为DOM遍历。如您所知,DOM 是一棵树,您实际上可以在不事先知道元素 id/type/其他内容的情况下遍历这棵树。

基本原理如下

  • el.childNodes 访问子元素列表
  • el.parentNode 访问父元素
  • nextSiblingpreviousSibling< /code> 用于下一个和上一个同级节点

有关更多信息,请参阅 [MDC DOM 页面](

Although the answers do give good ways to do it for this specific case....

The issue you're facing is called DOM-traversal. As you know, the DOM is a tree, and you can actually traverse the tree without knowing in advance the element id/type/whatever.

The basics are as follows

  • el.childNodes to access a list of children
  • el.parentNode to access the parent element
  • nextSibling and previousSibling for next and previous sibling nodes

For further info, see [MDC DOM pages](

临风闻羌笛 2024-12-01 20:29:22

这很简单:getElementsByTagName()?

It's quite simple: getElementsByTagName()?

始终不够 2024-12-01 20:29:22

您可以使用getElementsByTagName()

You could use getElementsByTagName()

美男兮 2024-12-01 20:29:22

循环遍历孩子们:

var div = document.getElementById('colorme');

var i, l, elem;

for (i = 0, l = div.childNodes.length; i < l; i++) {
    elem = div.childNodes[i];

    // Check that this node is an element
    if (elem.nodeType === 1) {
        elem.style.color = randomColorGenerator();
    }
}

Loop through the children:

var div = document.getElementById('colorme');

var i, l, elem;

for (i = 0, l = div.childNodes.length; i < l; i++) {
    elem = div.childNodes[i];

    // Check that this node is an element
    if (elem.nodeType === 1) {
        elem.style.color = randomColorGenerator();
    }
}
擦肩而过的背影 2024-12-01 20:29:22

在这种情况下,您可以使用:

var colormeDiv = document.getElementById('colorme');

var e1 = colormeDiv.getElementsByTagName('p');

var e2 = colormeDiv.getElementsByTagName('span');

获取 'colorme' div 内的两个元素。

In this case you can use:

var colormeDiv = document.getElementById('colorme');

var e1 = colormeDiv.getElementsByTagName('p');

var e2 = colormeDiv.getElementsByTagName('span');

to get the two elements inside 'colorme' div.

故人如初 2024-12-01 20:29:22

getElementById 只是 JavaScript 的 DOM 方法之一。它返回一个 HTMLElement DOM 对象,然后您可以查询该对象以查找子元素、父元素和同级元素。您可以使用它来遍历 HTML 并找到您需要的元素。这是JavaScript DOM HTMLObject 的参考

getElementById is just one of JavaScript's DOM methods. It returns an HTMLElement DOM object which you can then query to find child, parent and sibling elements. You could use this to traverse your HTML and find the elements you need. Here's a reference for the JavaScript DOM HTMLObject.

开始看清了 2024-12-01 20:29:22

[回答后,我意识到这不是对您完全解释的问题的答案,而是对您帖子标题中提出的问题的答案!]

一种很好的方法是在 Javascript 顶部声明一个全局变量引用文档,然后可以在任何地方(在每个函数中)使用:

<html>
<head>
<script type="text/javascript">

    // set a global var to acces the elements in the HTML document
    var doc = this;

    function testIt()
    {
        doc.blaat.innerHTML = 'It works!!';
    }
</script>
</head>
<body>
    <div id="blaat">Will this ever work..?!</div>
    <button onclick="testIt()">Click me and you'll see!</button>
</body>
</html>

当我到达“getElemenyById()”时,我的第一印象是它听起来像是一个将迭代 DOM 元素列表直到找到元素你需要;这肯定需要一些时间。通过上面的示例,您只需直接访问该元素即可。
我不确定这样是否真的节省了 CPU / 提高了速度,但至少感觉是这样:)

[after answering, I realised this is no answer to your fully explained question, but it is the answer to the question raised in the title of your post!]

One nice way of doing this is declaring a global var on the top of your Javascript that refers to the document, which can then be used everywhere (in every function):

<html>
<head>
<script type="text/javascript">

    // set a global var to acces the elements in the HTML document
    var doc = this;

    function testIt()
    {
        doc.blaat.innerHTML = 'It works!!';
    }
</script>
</head>
<body>
    <div id="blaat">Will this ever work..?!</div>
    <button onclick="testIt()">Click me and you'll see!</button>
</body>
</html>

As my first impression when I got to 'getElemenyById()' was that it sounds like a function that will iterate through the DOM's element list until it finds the element you need; this must take some time. With the above example, you simply access the element directly.
I'm not sure if I'm really saving CPU / adding speed this way, but at least it feels that way :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文