JavaScript 选择器

发布于 2024-12-03 15:42:35 字数 588 浏览 0 评论 0原文

如何在 JavaScript 中选择 DOM 元素?
例如:

<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,因此我无法将索引(正文)附加到上面。

有没有一种简单的方法来选择,例如

标签,它位于 desleft 的类名下? 我无法使用 jQuery 或任何其他库。

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>

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.

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.

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

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

发布评论

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

评论(6

執念 2024-12-10 15:42:35

您可以使用它来访问您的 H1:

var des = document.getElementsByClassName('des')
var fc = des[0].getElementsByTagName('h1')
alert(fc[0].innerHTML)

You can use this to get to your H1:

var des = document.getElementsByClassName('des')
var fc = des[0].getElementsByTagName('h1')
alert(fc[0].innerHTML)
天冷不及心凉 2024-12-10 15:42:35

w3.org 现在有选择器(http://www.w3.org/TR/selectors-api/#examples)。这里有两种在 Chrome 上对我有用的不同方法。您可能想要使用返回列表的 querySelectorAll 函数。

<script type="text/javascript">
//looks for <h1> tag under <div> with className "des"
showOff1 = function() {
  var x = document.querySelector(".des h1");
  alert(x.innerHTML);      
}
//looks for <div> tag with className "desleft" and then use previousSibling to traceback <h1> tag
showOff2 = function() {
  var y = document.querySelector("div.desleft");
  var z = y.previousSibling.previousSibling;
  alert(z.innerHTML);      
}
</script>
<body onload="showOff2();">

w3.org has selectors now (http://www.w3.org/TR/selectors-api/#examples). Here are 2 different ways that worked for me on Chrome. You may want to use querySelectorAll function that returns a list.

<script type="text/javascript">
//looks for <h1> tag under <div> with className "des"
showOff1 = function() {
  var x = document.querySelector(".des h1");
  alert(x.innerHTML);      
}
//looks for <div> tag with className "desleft" and then use previousSibling to traceback <h1> tag
showOff2 = function() {
  var y = document.querySelector("div.desleft");
  var z = y.previousSibling.previousSibling;
  alert(z.innerHTML);      
}
</script>
<body onload="showOff2();">
朦胧时间 2024-12-10 15:42:35

使用querySelectorAll

您可以使用querySelectorAll

// Will return a NodeList even if there is only one element found
var heading = document.querySelectorAll('.des > h1');

heading[1].style.color = 'red'; // NodeList is similar to an array

这将返回一个NodeList

使用 querySelector 返回找到的第一个元素:

var first_heading = document.querySelector('.des > h1');

first_heading.style.color = 'blue';

常用于id 选择器#single-header-id

这是一个演示

Use querySelectorAll

You can use querySelectorAll:

// Will return a NodeList even if there is only one element found
var heading = document.querySelectorAll('.des > h1');

heading[1].style.color = 'red'; // NodeList is similar to an array

This will return a NodeList.

or

Use querySelector to return the first element found:

var first_heading = document.querySelector('.des > h1');

first_heading.style.color = 'blue';

Commonly used with an id selector #single-header-id.

Here's a demo

︶ ̄淡然 2024-12-10 15:42:35
getElementsByTag()

您可以从一个函数开始,然后您可以过滤具有该类的 DOMElements。

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

现在重新阅读你的问题,为什么不直接给出你的 h1 的 id 呢?

DOM 遍历是 javascript 的突出问题之一(请输入 jQuery)。

一个简单的 getElementById() 会让您省去麻烦,并且所有 h1 上的 id 最终会比尝试制定算法通过其他方式选择它们要干净得多。

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

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

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

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

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.

眉目亦如画i 2024-12-10 15:42:35

如果您要选择 desleft 类的 第一个 元素之前的 h1,您始终可以这样做:

document.getElementsByClassName("desleft")[0].previousSibling.previousSibling

示例: http://jsfiddle.net/Xeon06/ZMJJk/

previousSibling 需求由于两者之间有空文本节点而被调用两次。这就是为什么使用库来做这些事情确实是最好的方法。

If you mean to select a h1 that is before the first element of class desleft, you could always do this:

document.getElementsByClassName("desleft")[0].previousSibling.previousSibling

Example: http://jsfiddle.net/Xeon06/ZMJJk/

previousSibling needs to be called twice because of the empty text node between the two. That's why using libraries to do this stuff is really the best way to go.

明媚如初 2024-12-10 15:42:35
var h1 = document.querySelector('.desleft').previousElementSibling;
  1. 使用选择器 '.desleft' 查找 className='desleft' 的元素
  2. 只需移回上一个元素(而不是上一个节点!)
var h1 = document.querySelector('.desleft').previousElementSibling;
  1. Find element with className='desleft' using selector '.desleft'
  2. Just move back to previous element (not to previous node!)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文