Jeff Sydor
Jeff Sydor

Reputation: 317

How to replace a string depending on the parent ID?

I'm testing a bunch of content and rather than deal with multiple pages, I'm just loading each element with PHP from one index page. Each "page" has a section of code with a breadcrumbs line. I'm trying to use JavaScript to target the "current" location line and replace it with the ID of its parent to show the current location.

Here's what I've already tried: JSfiddle

$('.show #filter.menu').each(function() {

  var parID = $(this).parent().attr('id');
  var parCL = $(this).parent().attr('class');

  if (parCL.search('show'))
    $('.menu .breadcrumbs .current').text($(this).text().replace('Here', parID));

});

Ideally I want "Here" to be replaced with the contents of the ID of the breadcrumb's parent. Such as: Home | Archives or Home | People.

But instead I'm getting Home | Home Archives.

I'm not sure what's going wrong.

Thanks

Upvotes: 0

Views: 130

Answers (1)

ahendwh2
ahendwh2

Reputation: 382

The problem lays in this line:

$('.menu .breadcrumbs .current').text($(this).text().replace('Here', parID));

In the context, $(this) refers to the current element of the loop from the first line. So $(this).text() returns "Home Here" because both words are in the same section width the id "filter". Then your code replaces "Here" width the parent id. So the result is "Home archives".

So instead of replacing "Here" you could just set the text of .current to the parent ID:

$('.menu .breadcrumbs .current').text(parID);

Upvotes: 1

Related Questions