Reputation: 241
i want to add attribute to li
with the href link but without the #
for example:
<ul id="menu-1" class="menu">
<li id="menu-item-17" class="menu-item"><a href="#firstPage">first Page</a></li>
<li id="menu-item-13" class="menu-item"><a href="#secondPage">second Page</a></li>
<li id="menu-item-14" class="menu-item"><a href="#thirdPage">third Page</a></li>
</ul>
will be
<ul id="menu-1" class="menu">
<li id="menu-item-17" class="menu-item" data-menuanchor="firstPage"><a href="#firstPage">first Page</a></li>
<li id="menu-item-13" class="menu-item" data-menuanchor="secondPage"><a href="#secondPage">second Page</a></li>
<li id="menu-item-14" class="menu-item" data-menuanchor="thirdPage"><a href="#thirdPage">third Page</a></li>
</ul>
here is the code that will add attribute to li
jQuery(document).ready( function($) {
$('#menu-1 li').attr('data-menuanchor', '**here i need to add the href without #**')
});
Upvotes: 2
Views: 533
Reputation: 33218
You can use String.prototype.replace() to achieve that:
jQuery(document).ready(function($) {
//get the url
var oldUrl = $("#menu-item-1").children().attr("href");
//remove # using String.prototype.replace()
var url = oldUrl.replace(/#/, "");
//add attribute data-menuanchor to li element
$('#menu-1 li').attr('data-menuanchor', url);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu-1" class="menu">
<li id="menu-item-1" class="menu-item"><a href="#firstPage">first Page</a>
</li>
</ul>
Also in one line:
jQuery(document).ready(function ($) {
$('#menu-1 li').attr('data-menuanchor', $("#menu-item-1").children().attr("href").replace(/#/, ""));
});
Also to add the data-menuanchor
to all li
elements you need an iterator. Here an example using jquery .filter()
jQuery(document).ready(function($) {
$('#menu-1 li').filter(function() {
$(this).attr('data-menuanchor', this.children[0].hash.replace(/#/, ""));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu-1" class="menu">
<li id="menu-item-17" class="menu-item"><a href="#firstPage">first Page</a>
</li>
<li id="menu-item-13" class="menu-item"><a href="#secondPage">second Page</a>
</li>
<li id="menu-item-14" class="menu-item"><a href="#thirdPage">third Page</a>
</li>
</ul>
Upvotes: 2
Reputation: 1442
Check this fiddle: http://jsfiddle.net/uu5nbn7r/
Try this:
$(document).ready( function($) {
$('#menu-1 li').each(function(i, val){
$(this).attr('data-menuanchor',$(this).find('a').attr('href').replace('#',''));
});
});
Upvotes: 0
Reputation: 1
This should do the trick:
$(function(){
$('li', $('#menu-1')).each(function(){
$(this).attr('data-menuanchor', $('a', $(this)).attr('href').replace('#',''));
});
})
Upvotes: 0