Reputation: 483
Let's say my section contains the pages "Red", "Green" and "Blue". Each page has the title in a H1 tag as well as a shared #sidebar navigation showing all three links. How can I get jQuery to detect the text entered in the H1, find the same text in #sidebar, and add a class to the #sidebar link if a match is found?
HTML:
<h1>Red</h1>
<div id="sidebar">
<a href="#">Red</a><br>
<a href="#">Green</a><br>
<a href="#">Blue</a>
</div>
CSS:
#sidebar { float: right; }
.current-section { background: red; }
Sorry - I'm a jQuery beginner at best. Here's a Fiddle: http://jsfiddle.net/BxCgT/
Upvotes: 1
Views: 167
Reputation: 38147
Something like this might work ...
// get title text
var title = $('h1').text();
// loop anchors in #sidebar
$('#sidebar a').each(function() {
// if anchor text matches title
if($(this).text() == title) {
// add a class
$(this).addClass(<yourclass>);
}
});
Relevant docs -> .text()
.each()
and .addClass()
I've made an assumption your code looks something like this :
<h1>Red</h1>
<div id="sidebar">
<a href="red.html">Red</a><br>
<a href="green.html">Green</a><br>
<a href="blue.html">Blue</a>
</div>
Upvotes: 2