简体   繁体   中英

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.

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> 

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 + '">');

 // 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM