2

How i do apply attr to all href's on my page. For example: I have :

<ul>
    <li><a href="mylink1">mytext1</a></li>
    <li><a href="mylink2">mytext2</a></li>
    <li><a href="mylink3">mytext3</a></li>
</ul>

I need:

<ul>
    <li><a href="javascript:myFunc(mylink1)">mytext1</a></li>
    <li><a href="javascript:myFunc(mylink2)">mytext2</a></li>
    <li><a href="javascript:myFunc(mylink3)">mytext3</a></li>
</ul>

I need do this without adding new id's, classes and etc. Use Js and jQuery. Please, help! :)

Doctor Lol
  • 45
  • 1
  • 6

7 Answers7

3

Something like this should work:

$("ul li a").each(function(i, a) {
    a = $(a);
    a.attr('href', 'javascript:myFunc("' + a.attr('href') + '")');
});

Demonstration

Note: this will apply this to only links within ul lists. To apply to all a tags across the entire page, use $("a")... instead.

Also, this method may fail if the href attributes contain certain characters like " or \. If this is a possibility, then this is a bit safer:

$("ul li a").each(function(i, a) {
    a = $(a);
    a.attr('href', 'javascript:myFunc(' + JSON.stringify(a.attr('href')) + ')');
});
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
1

You can try like

$('a').each(function () {
    var att = $(this).attr('href');
    $(this).attr("href", "javascript:myFunc(" + att + ")");
});
Praveen
  • 55,303
  • 33
  • 133
  • 164
1

Using jQuery:

$("a[href^='mylink']").on('click', function(e) {
    e.preventDefault();
   myFunc($(this).attr("href"));
});
Jonas Grumann
  • 10,438
  • 2
  • 22
  • 40
1

this shoud do what you need:

$("a").each( function() {
  var url = $(this).attr('href');
  $(this).attr('href', 'javascript:myFunc("'+url+'")');
});
webdev-dan
  • 1,339
  • 7
  • 10
1

Instead of modifying the href assign the event handler in the actual Javascript:

$("[href]").click(function(e){
    e.preventDefault();
    myFunc(this.href);
});

function myFunc(value){
   alert(value);
}

JS Fiddle: http://jsfiddle.net/Rs9RH/

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
0

Try This:

$('li a').each(function(){
$(this).attr('href',"javascript:myFunc("+$(this).attr('href')+")");
})

WORKING FIDDLE

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

I think this could works:

$("a[href^='mylink']").each(function () {
  var url = $(this).attr('href');
  $(this).attr("href", 'javascript:myFunc("'+url+'")')
})
Donnie Rock
  • 552
  • 1
  • 14
  • 27