Mystikal_KK44
Mystikal_KK44

Reputation: 41

how to find string in html tag and replace using javascript/jquery

I do not know how to find a string in the html tag and replace it with another one. I will show it on an example.

I have something like that

<a class="test" data-value="/content/dam/tetris-templating/framework/svg/ic-editorial-07.svg"></a>

And I would like to get such an effect

<a class="test"> <img-src="/content/dam/tetris-templating/framework/svg/ic-editorial-07.svg"></a>

Does anyone have any idea? I'm sorry for my level of English.

Upvotes: 0

Views: 40

Answers (3)

user3805605
user3805605

Reputation: 66

// If It has multiple hyperlink tag then
$('a').each(function(){
        if($(this).data('value')!=undefined){
            $(this).append(function(){
              return '<img src="'+$(this).attr("data-value")+'">';
            }).removeAttr("data-value");
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="test" data-value="/content/dam/tetris-templating/framework/svg/ic-editorial-07.svg"></a>

Upvotes: 0

Ted
Ted

Reputation: 4057

Assuming that you are new in JavaScript and/or jQuery, I've made a step-by-step example of a solution:

// create a pointer to your anchor
var $yourAnchor = $('.test')

// copy data attribute
var $hdata = $yourAnchor.data('value');

// remove attribute
$yourAnchor.removeAttr('data-value');

// insert html
$yourAnchor.html('<img src="' + $hdata + '">');

Upvotes: 0

void
void

Reputation: 36703

You can first append the img and then remove the attribute data-value.

See the code below:

$("a").append(function(){
  return '<img src="'+$(this).attr("data-value")+'">';
}).removeAttr("data-value")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="test" data-value="/content/dam/tetris-templating/framework/svg/ic-editorial-07.svg"></a>

Upvotes: 4

Related Questions