+ 2

Get element inside element by class - JavaScript

How can i get first or last <p> element in Class by classname? <div class ="demo"> <p>some text</p> <p>some other text</p> </div>

9th Apr 2018, 9:28 AM
Habib Najafi
Habib Najafi - avatar
7 Respuestas
9th Apr 2018, 9:37 AM
Rull Deef 🐺
Rull Deef 🐺 - avatar
+ 3
Or if you use jQuery: $("div .demo p:first")
9th Apr 2018, 9:32 AM
Rull Deef 🐺
Rull Deef 🐺 - avatar
+ 3
var demo = document.getElementsByClassName("demo")[0]; //first element with class demo var pElms = demo.getElementsByTag("p"); pElms[0] // first element pElms[(pElms.length - 1)] //last element
9th Apr 2018, 9:37 AM
Damyan Petkov
Damyan Petkov - avatar
+ 2
I think 'children' method will help
9th Apr 2018, 9:31 AM
Rull Deef 🐺
Rull Deef 🐺 - avatar
+ 1
Thank you Rull Deef and Damyan Petkov
9th Apr 2018, 9:42 AM
Habib Najafi
Habib Najafi - avatar
+ 1
var p = document.querySelectorAll(".demo p"); console.log("first p: " + p[0].innerText); console.log("last p: " + p[p.length-1].innerText);
9th Apr 2018, 10:02 AM
Calviղ
Calviղ - avatar
0
No jQuery
9th Apr 2018, 9:33 AM
Habib Najafi
Habib Najafi - avatar