Question

HTML..

<div class="row">
   <div>
      <b>Title A</b> <a href="#">Link 1</a> <a href="#">Link 2</a>
   </div>
   Content A
</div>
<div class="row">
   <div>
      <b>Title B</b> <a href="#">Link 1</a> <a href="#">Link 2</a>
   </div>
   Content B
</div>
<div class="row">
   <div>
      <b>Title C</b> <a href="#">Link 1</a> <a href="#">Link 2</a>
   </div>
   Content C
</div>

jQuery..

So far my JS adds a "Link 3" link after each "Link 2"..

$("a:contains('Link 2')").each(function(){
   $(this).after(' <a href="#">Link 3</a>');
});

For each item in the loop how would I access the title.

$("a:contains('Link 2')").each(function(){
   // I need to find the title string for each row. So is there a way to find elements before the $(this) identifier?
   $(this).after(' <a href="#">Link 3</a>');
});
Was it helpful?

Solution

You can get the previous sibling by using the .prev() method. You can do that, or you can get the links .parent(), and then .find() the first <b> tag.

<p>Something Here</p> <!-- This becomes red -->
<p class="pickme">Hello World</p>

$(document).ready(function(){
  $(".pickme").prev().css("color","red");
});

or

<p>Something Here</p> <!-- this becomes green -->
<p class="pickme">Hello World</p>

$(document).ready(function(){
  $(".pickme").parent().find("p:first").css("color", "green");
});

OTHER TIPS

If you add a class, such as "rowTitle" to all of your bold tags that are wrapping your titles, you should be able to do:

$("a:contains('Link 2')").each(function(){
   $(this).parent().find(".rowTitle").html
});

Or something fairly similar. The jQuery Docs are fairly comprehensive, and a quick search there should help you find what you're looking for.

I'm not a jQuery expert, but I believe that's fairly close to working. Perhaps someone a bit more versed in the matter could elaborate on my answer (as I wouldn't mind learning as well).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top