Welcome to WebmasterWorld Guest from 54.167.213.22

Forum Moderators: open

Message Too Old, No Replies

Find Matching Content JQuery

     
9:08 pm on Feb 17, 2012 (gmt 0)



I want to take and bold (add a class) to a list element that's content matches my h1 tag.

The code I have below doesn't work but, I think I'm on the right track. Could somebody help me out? Any help is appreciated!

<style type="text/css">
.selectedListItem{font-weight:bold;}
</style>

<script type="text/javascript">
$(document).ready(function () {
var h1_text = $('h1').text();
var sidemenu_link = $('#sideMenu a').text();
$(sidemenu_link == h1_text).parents("li").addClass("selectedListItem")
});
</script>

<h1>My Page Name</h1>

<ul id="sideMenu">
<li><a href="#">sample 1</a></li>
<li><a href="#">sample 2</a></li>
<li><a href="#">sample 3</a></li>
<li><a href="#">My Page Name</a></li>
<li><a href="#">sample 5</a></li>
</ul>
12:07 am on Feb 18, 2012 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



$(sidemenu_link == h1_text)
evaluates to $(true) or $(false) ?

$('#sideMenu a').text() gets the combined text content.

either use the contains selector [api.jquery.com...] that will probably suffice, "text within" rather than exact match.

or use .each to test each individually.
2:04 pm on Feb 21, 2012 (gmt 0)



Thanks that helps point me in the right direction but, when I try to use a variable it doesn't work. Can this be done? Am I just overlooking something? Thanks again!

<script type="text/javascript">
$(document).ready(function () {
var h1_text = $('h1').text();
$("#sideMenu a:contains('h1_text')").addClass("selectedListItem");

/* Using exact text works
$("#sideMenu a:contains('My Page Name')").addClass("selectedListItem");
*/
});

</script>

<style type="text/css">
.selectedListItem{font-weight:bold;}
</style>

</head>

<body>

<h1>My Page Name</h1>

<ul id="sideMenu">
<li><a href="#">sample 1</a></li>
<li><a href="#">sample 2</a></li>
<li><a href="#">sample 3</a></li>
<li><a href="#">My Page Name</a></li>
<li><a href="#">sample 5</a></li>
</ul>
2:35 pm on Feb 21, 2012 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month




$(document).ready(function () {
var h1_text = $('h1').text();
$('#sideMenu a').each(function(index, el){
if (h1_text == $(el).text()) {
$(el).addClass("selectedListItem");
}
});
});
2:40 pm on Feb 21, 2012 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



Or:


$(document).ready(function () {
var selector = "#sideMenu a:contains(" + $('h1').text() + ")";
$(selector).addClass("selectedListItem");
});
3:28 pm on Feb 21, 2012 (gmt 0)



That is really cool! I like the second example, it's simple and easy enough to add more variables say I wanted to find H2. Thank you very much!
 

Featured Threads

Hot Threads This Week

Hot Threads This Month