JavaScript选择器 [英] javascript selectors

查看:113
本文介绍了JavaScript选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在JavaScript中选择DOM元素?

例如:

How does one select DOM elements in javascript?
Like for example:

<div class="des">
    <h1>Test</h1>
        <div class="desleft">
          <p>Lorem Ipsum.</p>
        </div>
        <div class="Right">
           <button>Test</button>
        </div>
</div>

现在我如何选择 h1 ?这只是一个较大页面的一部分,所以不能使用 getElementsByTagName(),因为其他人可能会被选中。此外,由于文档中可能还有其他 h1 ,我无法将索引(正文)附加到上面。

Now how do i select h1? This is just a part of a bigger Page, so cannot use getElementsByTagName(), since others might get selected. Also since there might be other h1's in the document later, i cannot attach the index(body's) to above.

是否有一种简单的选择方式,例如< h1> 标签,该类别名为 desleft
我不能使用jQuery或其他库。

Is there a simple way to select, say <h1> tag which is under the classname of desleft? I cannot use jQuery or any other libraries.

推荐答案

getElementsByTag()

将是一个您可以开始的功能,然后您可以过滤具有

Would be a function that you can start with, and then you can filter for the DOMElements that have the class.

var h1_array = document.getElementsByTag('h1');

var h1_class_array = [];
for (var i=0, len=h1_array.length; i < len; i++) {
    if (h1_array[i].className.indexOf('classname') !== -1) {
        h1_class_array.push(h1_array[i]);
    }
}

.indexOf 函数返回 -1 如果在haystack中找不到针。

The .indexOf function returns -1 if the needle is not found in the haystack.

阅读你的问题,为什么不只是给你的h1的id?

Now re-reading your question, why not just give your h1's id's ?

DOM遍历是javascript的一个引人注目的问题(输入jQuery)。

DOM traversal is one of javascript's glaring issues (enter jQuery).

一个简单的 getElementById()会节省你的头痛,而所有h1上的ids最终会比尝试制定算法选择更干净他们以其他方式。

a simple getElementById() would save you a headache, and ids on all your h1's would be much cleaner in the end than trying to formulate an algorithm to select them by other means.

这篇关于JavaScript选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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