简体   繁体   English

使用没有 getElementById 的 javascript 到达 HTML 元素

[英]reach a HTML element using javascript without getElementById

I'm new to javascript.我是 javascript 的新手。 I created this div called colorme.我创建了这个名为 colorme 的 div。 I can successfully color it via javascript.我可以通过 javascript 成功地给它上色。 Now assuming i want to change the background of <p>...</p> , or <span> ,etc how do i reach it via Javascript?现在假设我想更改<p>...</p><span>等的背景,我如何通过 Javascript 到达它? (no jquery). (没有jQuery)。

Like document.getElementById() would work on the div and i reach it.就像 document.getElementById() 可以在 div 上工作,我可以达到它。 Now i cannot keep giving unique id's to all the elements.现在我不能继续为所有元素提供唯一的 id。 How do i reach the inner elements like <p> or <span> , etc?我如何到达<p><span>等内部元素?

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

You can use the element that you've found as a context for getElementsByTagName .您可以将找到的元素用作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 .请注意, spans是一个 NodeList - 类似于数组 - 包含colorme中的所有span元素。 If you want the first one (indeed, the only one in your code sample), use spans[0] .如果您想要第一个(实际上,代码示例中的唯一一个),请使用spans[0]

You should check out the many DOM traversal functions provided in standard javascript.您应该查看标准 javascript 中提供的许多 DOM 遍历函数。

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

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

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

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) - eg document.querySelector('#colorme p') .如果您只关心体面的浏览器, document.querySelector (返回第一个匹配节点)和document.querySelectorAll (返回 NodeList) - 例如document.querySelector('#colorme p')

  2. HTMLElement.getElementsByTagName() (returns a NodeList) - eg document.getElementById('colorme').getElementsByTagName('p')[0] HTMLElement.getElementsByTagName() (返回 NodeList) - 例如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). HTMLElement.children等 - document.getElementById('colorme').children[0].firstChild可能是一个文本节点,有很多有趣的 DOM 内容可以进入,链接到的 quirksmode DOM 介绍是好东西) .

Although the answers do give good ways to do it for this specific case....尽管答案确实为这种特定情况提供了很好的方法......

The issue you're facing is called DOM-traversal .您面临的问题称为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.如您所知,DOM 是一棵树,您实际上可以在不事先知道元素 id/type/whatever 的情况下遍历树。

The basics are as follows基本情况如下

  • el.childNodes to access a list of children el.childNodes访问子列表
  • el.parentNode to access the parent element el.parentNode访问父元素
  • nextSibling and previousSibling for next and previous sibling nodes nextSiblingpreviousSibling用于下一个和上一个兄弟节点

For further info, see [MDC DOM pages](有关详细信息,请参阅 [MDC DOM 页面](

It's quite simple: getElementsByTagName()?这很简单:getElementsByTagName()?

You could use getElementsByTagName()您可以使用getElementsByTagName()

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();
    }
}

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.获取'colorme' div 中的两个元素。

getElementById is just one of JavaScript's DOM methods. getElementById 只是 JavaScript 的 DOM 方法之一。 It returns an HTMLElement DOM object which you can then query to find child, parent and sibling elements.它返回一个 HTMLElement DOM object,然后您可以查询它以查找子元素、父元素和兄弟元素。 You could use this to traverse your HTML and find the elements you need.您可以使用它来遍历您的 HTML 并找到您需要的元素。 Here's a reference for the JavaScript DOM HTMLObject .是 JavaScript DOM HTMLObject 的参考

[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):一种很好的方法是在 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>

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;当我到达“getElemenyById()”时,我的第一印象是它听起来像是一个 function,它将遍历 DOM 的元素列表,直到找到您需要的元素; 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:)我不确定我是否真的以这种方式节省 CPU / 增加速度,但至少感觉是这样的:)

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

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