0

I am developing an application using HTML and JQuery (and AngularJS). I am new to using JQuery and have a question. Let's assume I have this HTML file:

    <div class="my_class">1</div>
    <p ng-click="my_method()">MY FIRST PARAGRAPH</p>
    <div class="my_class">2</div>
    <p ng-click="my_method()">MY SECOND PARAGRAPH</p>
    <div class="my_class">3</div>
    <p ng-click="my_method()">MY THIRD PARAGRAPH</p>
    <div class="my_class">4</div>
    <p ng-click="my_method()">MY FOURTH PARAGRAPH</p>
    <div class="another_class">something in here..</div>
    <div class="my_class">5</div>

If in the my_method() method I want to use JQuery code to dynamically change the style of a SINGLE <div> element associated with the my_class class I don't know how to do it. I know that the following code:

$(".my_class")

will select all the elements associated with the my_class class. But how do I, for example, select exactly <div class = "my_class"> 4 </div> if I click on <p ng-click="my_method()">MY FOURTH PARAGRAPH</p> (In this case the div I'm interested in is the closest to the top of the point where I clicked)?

wishyouwerehere
  • 163
  • 1
  • 3
  • 8
  • 1
    You want the _previous_ `div.my_class` element. You should be able to find a solution with that here on SO or in the [jQuery Learning Center](https://learn.jquery.com) – Andreas Oct 22 '20 at 10:22

2 Answers2

2

Yuo can pass the paragraph element as parameter of your function:

<p ng-click="my_method(this)">MY FOURTH PARAGRAPH</p>

and then inside your function you can find the div with prev()

function my_method(element) {
    var myDiv = $(element).prev();
}
Nicholas Nur
  • 228
  • 2
  • 12
2

assuming you want to keep the structure same, try this, in your my_method(event) accept event.

my_method(event) {
  let paragraphElement = event.target;
  let divElement = $(paragraphElement).prev();

  // now you can change styles on that specific div
  divElement.css( "background-color", "red" )
}

There are number of ways to do this, as Jquery provides lot of methods to target elements. Suppose you enclosed those paragraphs into the div elements, you can select div by

let divElement = $(paragraphElement).parent();
Akash Sarode
  • 387
  • 2
  • 13