views:

85

answers:

4

Hi, I am a javascript noob.

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

Thanks a lot! Tom

+1  A: 

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>
m_oLogin
I agree with you. It is much less prone to breaking to attach an id. Then when you insert a new paragraph and this becomes the third paragraph all of your DOM traversals wont' break.
Keith Rousseau
+4  A: 

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)');
reko_t
In jQuery, you have to select the DOM node specifically: `$('div.box p:eq(1)').get(1)`. Otherwise, you just get an jQuery object, and that is lacking literally all DOM interfaces.
Boldewyn
Actually with .get(0) or just [0], because p:eq(1) already selected the second paragraph.
reko_t
+1  A: 
<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>
David
sorry - I misread the question. This answer would apply to "div#box p[1]"
David
A: 

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");
Boldewyn
@Boldewyn: `querySelector` and `querySelectorAll` are both supported by IE8. In fact, IE8 had it (March 2009) before Firefox (v3.5 June 2009)
Andy E
@Andy E: Thanks for pointing out. However, this you call support: http://ejohn.org/blog/selectors-api-test-suite-in-ie8/ ? However, you got a point, and I'll correct the answer.
Boldewyn