JavaScript 选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7353641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript selectors
提问by Aaditi Sharma
How does one select DOM elements in javascript?
Like for example:
如何在 javascript 中选择 DOM 元素?
例如:
<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.
现在我该如何选择h1
?这只是更大页面的一部分,因此不能使用getElementsByTagName()
,因为其他人可能会被选中。此外,由于h1
稍后文档中可能还有 other ,我无法将索引(正文)附加到上面。
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.
有没有一种简单的方法来选择,比如<h1>
类名下的标签desleft
?我不能使用 jQuery 或任何其他库。
采纳答案by jondavidjohn
getElementsByTag()
Would be a function that you can start with, and then you can filter for the DOMElements that have the class.
将是一个您可以开始使用的函数,然后您可以过滤具有该类的 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]);
}
}
The .indexOf
function returns -1
if the needle is not found in the haystack.
如果在大海捞针中找不到针,则该.indexOf
函数返回-1
。
Now re-reading your question, why not just give your h1's id's ?
现在重新阅读您的问题,为什么不直接提供您的 h1 的 id 呢?
DOM traversal is one of javascript's glaring issues (enter jQuery).
DOM 遍历是 javascript 的突出问题之一(进入 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.
一个简单的方法getElementById()
会让你头疼,而且你所有的 h1 上的 id 最终会比试图制定一个算法来通过其他方式选择它们更清晰。
回答by Diodeus - James MacFarlane
You can use this to get to your H1:
您可以使用它来获得您的 H1:
var des = document.getElementsByClassName('des')
var fc = des[0].getElementsByTagName('h1')
alert(fc[0].innerHTML)
回答by StackRover
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.
w3.org 现在有选择器 (http://www.w3.org/TR/selectors-api/#examples)。以下是在 Chrome 上对我有用的 2 种不同方式。您可能想要使用返回列表的 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();">
回答by hitautodestruct
Use querySelectorAll
使用 querySelectorAll
You can use 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
This will return a NodeList.
这将返回一个NodeList。
or
或者
Use querySelector
to return the first element found:
使用querySelector
返回找到的第一个元素:
var first_heading = document.querySelector('.des > h1');
first_heading.style.color = 'blue';
Commonly used with an id selector #single-header-id
.
通常与 id 选择器一起使用#single-header-id
。
回答by Alex Turpin
If you mean to select a h1
that is beforethe firstelement of class desleft
, you could always do this:
如果你的意思是选择一个h1
是之前的第一类的元素desleft
,你总是可以做到这一点:
document.getElementsByClassName("desleft")[0].previousSibling.previousSibling
Example: http://jsfiddle.net/Xeon06/ZMJJk/
示例: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.
previousSibling
由于两者之间存在空文本节点,因此需要调用两次。这就是为什么使用库来做这些事情真的是最好的方法。
回答by Volodymyr Fedorov
var h1 = document.querySelector('.desleft').previousElementSibling;
- Find element with className='desleft' using selector '.desleft'
- Just move back to previous element (not to previous node!)
- 使用选择器 '.desleft' 查找 className='desleft' 的元素
- 只需移回上一个元素(而不是上一个节点!)