开发者

Javascript DOM howto?

开发者 https://www.devze.com 2022-12-24 06:18 出处:网络
I am a javascript no开发者_如何学Cob. I would like to select the second \'p\' element of the div.box.

I am a javascript no开发者_如何学Cob.

I would like to select the second 'p' element of the div.box. How do I do this?

Thanks a lot! Tom


To get second p element of div with class box you'd do this:

var paragraph = null;
var divs = document.findElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
    var div = divs[i];
    if (div.class == 'box') {
        var paragraphs = div.getElementsByTagName('p');
        if (paragraphs.length > 1)
            paragraph = paragraphs[1];
        break;
    }
}

The paragraph would then be in the paragraph variable (or null if it wasn't found).

However you can do this much easier with a library such as jQuery:

var paragraph = $('div.box p:eq(1)');


Without using jQuery, the basic method would be to attach an unique ID to your Dom element

<p id="second_p_elmt"> [...] </p>

and then accessing it through the getElementById() method:

<script ...>
  var second_p_elmt = document.getElementById('second_p_elmt');
</script>


<script type="text/javascript">
    var boxElem = document.getElementById('box'),
        pElems = boxElem.getElementsByTagName('p'),
        whatYouWant = pElems[1]; // [1] is the second element in the response from getElementsByTagName
</script>


You have several options. As stated above, you could use one of the excellent frameworks, like jQuery or prototype. Or you give the <p/> an ID, that you can use simply with document.getElementById().

Then, as reko_t pointed out, without the above, you must write a lengthy DOM traversing code (which is preferable, if you don't use JS frameworks elsewhere, over embedding them only for this task).

In the most recent browsers (namely, IE>=8, FF>=3.5, recent Opera and Safari > 3) you can also use this simple snippet:

var p = document.querySelectorAll("div.box p");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号