Javascript - Getting element
<div>
<p>
<a></a>
</p>
</div>
In the code above, for jQuery, we can use $('div p a')
to get the <a>
element, but in javascript, how can we do get <a>
element like $('div p a')
?
Updated 2
If I have many<a>
element and I don't know the index of the specific <a>
element, I just know this s开发者_开发知识库pecific <a>
element is under <div id="some">
, how can I get the <a>
element by javascript?you can get the div
then get the a
tag within it JSFiddle example
HTML
<div>
<p>
<a></a>
</p>
</div>
<div id="some">
<a href="#">my a tag</a>
</div>
JavaScript
var elems = document.getElementById('some').getElementsByTagName('a');
alert(elems[0].innerHTML);
If you have some more info, like the IDs of the elements, you can use document.getElementById('id')
. Otherwise, you can traverse the DOM tree, see this:
- http://www.permadi.com/tutorial/domTree/index.html
You can also use xpath:
- https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript
For xpath, take a look at this tutorial (examples part of the tutorial, actually):
- http://www.w3schools.com/xpath/xpath_examples.asp
In your example, the xpath should be: //div/p/a
, which will select all such element trees, if there are more then one.
See method ’document.getElementsByTagName’
http://www.w3schools.com/Dom/met_document_getelementsbytagname.asp
Using this method. You would first iterate all divs, and on those divs get all paragraphs, and then the same thing for the anchors.
jQuery is Javascript; I think you meant standard Javascript DOM functions. Also, it is better to use jQuery for this: find out what is wrong, instead of trying to reinvent the wheel. One thing will lead to another. It will be better in the long run to have a concrete library like jQuery backing you. If you really need to use CSS3 selectors like this, use the Sizzle library. Sizzle was created by the jQuery group for this purpose. (I am not associated with jQuery or Sizzle except for being a satisfied user).
These days we have:
- document.querySelector
- document.querySelectorAll
and both of these can use the CSS selectors in the same way that jQuery does to get the required elements.
var one = document.querySelector('#some span');
document.querySelectorAll('.resultLine')[0].innerHTML = 'We grabbed: "' + one.id + '" with querySelector(\'#some span\')';
var all = document.querySelectorAll('#some span');
var idList = '';
for (i = 0; i < all.length; i++) {
if (i>0) {
idList += ', ';
}
idList += '"' + all[i].id + '"'
}
document.querySelectorAll('.resultLine')[1].innerHTML = 'We grabbed: ' + idList + ' with querySelectorAll(\'#some span\')';
#result {
color: red;
background: black;
border: red 1px solid;
}
.resultLine {
display: block;
}
<p id="some">
<span id="one">1</span>
<span id="two">2</span>
<span id="three">3</span>
</p>
<p id="result">
<span class="resultLine"></span>
<span class="resultLine"></span>
</p>
精彩评论