Home > database >  Get child nodes
Get child nodes

Time:06-17

I have this code

<div id="page1-div" style="position:relative;width:1347px;height:1189px;">
        <img width="1347" height="1189" src="target001.png" alt="background image" />
        <p style="position:absolute;top:218px;left:209px;white-space:nowrap" >Mario</p>
        <p style="position:absolute;top:218px;left:263px;white-space:nowrap" >Lopez</p>
        <p style="position:absolute;top:218px;left:827px;white-space:nowrap" >18987456O</p>
        <p style="position:absolute;top:395px;left:183px;white-space:nowrap" >25</p>
        <p style="position:absolute;top:395px;left:402px;white-space:nowrap" >Fisica y Química</p>
        <p style="position:absolute;top:433px;left:298px;white-space:nowrap" >Ninguna</p>
        <p style="position:absolute;top:502px;left:633px;white-space:nowrap" >230</p>
</div>
<div id="page2-div" style="position:relative;width:1347px;height:1189px;">
        <img width="1347" height="1189" src="target002.png" alt="background image" />
        <p style="position:absolute;top:149px;left:300px;white-space:nowrap" >25</p>
        <p style="position:absolute;top:149px;left:565px;white-space:nowrap" >Fisica y Química</p>
        <p style="position:absolute;top:149px;left:984px;white-space:nowrap" >fevev</p>
        <p style="position:absolute;top:172px;left:425px;white-space:nowrap" >fevevvvev</p>
        <p style="position:absolute;top:172px;left:912px;white-space:nowrap" >Juan Soler</p>
        <p style="position:absolute;top:195px;left:319px;white-space:nowrap" >Ana&#160;Abarca</p>
        <p style="position:absolute;top:195px;left:981px;white-space:nowrap" >9:30-14:30</p>
</div>`

I want to get all p elements inside both divs to set different id attributes (or change the values of the class attributes if that is easier) to each of them so I can modify the styles in a css file. But I don´t know how to properly access the p elements inside the two divs

CodePudding user response:

You would need to get the div elements, then on those elements, you can do querySelectorAll('p') to get an array of the paragraphs.

Something like this.

const firstDiv = document.querySelector('#page1-div')
const firtDivParagraphs = firstDiv.querySelectorAll('p')

If you just want to get all the paragraphs and you don't care about where they are you can of course query them on the document object instead. You could also be more generic to access all paragraphs following div's:

const paragraphs = document.querySelectorAll('div > p')

Essentially any valid CSS selector can be used with querySelector or querySelectorAll.

Without knowing what exactly you are trying to do, it would probably be better using classes for the divs, then you could query them at the same time, instead of having to query them separately.

const paragraphs = document.querySelectorAll('.div-class > p')
  • Related