how to target an external div in javascript

99 views Asked by At

I have this situation:

<div id="first">
  <div>
    <p>text</p>
  </div>
</div>
<div id="second">
   <div>
      <button class="button">click</button>
   </div>
</div>
...
<div id="first"> ... </div>
<div id="second"> ... </div>
...

and so on, the structure repeats.

This structure is created dynamically so I can't use any specific class nor id for the first div.

I need to retrieve the text in the first div when I hit the button in the second div.

(NOTE: I need a pure javascript solution, not a jQuery solution)

Thanks

1

There are 1 answers

0
jfriend00 On

Assuming you have an event handler for the button click, you could do this from that event handler:

function buttonClickHandler(e) {
    var first = this.parentNode.parentNode.previousSibling;
    var paragraphs = first.getElementsByTagName("p");
    var text = paragraphs[0].textContent;
}

If you have common and known class names on the the divs marked first and second, then you can make your Javascript code much more insulated from markup changes which is generally a good idea.


P.S. I presume you know that you should't have duplicate id values in your HTML. This code doesn't use them, but you should be using class names instead of id values if you're going to have duplicates.