views:

237

answers:

2

I have a string which contains text and some <a> tags in it; I want to know how I can select a tag from the variable and loop it. I tried the following but it didn't work:

var text = `some string here with <a href="#link">http:something.com</a> more string and more links also`;

$('a', text).each(function() {

      var string = $(this).html();
      $(this).html(string.substring(0, length-1)+(string.length > length ? end : ''));

     });
A: 

Replace

$('a', text).each(function() {

with

$(text, 'a').each(function() {

and see if it works.

rahul
your selector also worked, but it gave problem on $(this).html('adding new value');btw do you know how i can put same value in text variable after changing it?
Basit
+5  A: 

You need to wrap the text in a div (or other element) then find() it:

var text = 'some string here with <a href="#link">http:something.com</a> more string and more links also';

text = $('<div>' + text + '</div>');

text.find('a').each(function() {
    var length = 10;
    var end = '...';

    var string = $(this).html();
    $(this).html(string.substring(0, length) + (string.length > length ? end : ''));
});

var text = text.html();

// Put it into a textarea
$('#myTextarea').val(text);
Greg
greg thank you for answering and its working, but only one problem left is.. how can i change the text init and assign it back at same position as it was before?
Basit
The code you have is pretty much working if you define length and end. You just need to grab `text.html()` after you run it.
Greg
nope, text.html() is not working, my row loops gets ended when i run this text.html(), it wont run anymore javascript after it and wont show any error eaither in firebug.
Basit
solved: (ofcourse with greg tips (: ) http://stackoverflow.com/questions/1553784/jquery-each-loop-and-replace-to-same-location/1554094#1554094
Basit