简体   繁体   中英

How to add text from span tag to data-attr by jQuery?

How to add text from span tag to data-attr?

Example:
I have this code

 <div class="clearfix colelem" id="u92-5"><!-- content --> <p>Icon<span id="u92-2">iconsymbol</span></p> </div> 

And I want to add iconsymbol to data-attr="iconsymbol" of the same element like a:

 <div class="clearfix colelem" id="u92-5" data-attr="iconsymbol"><!-- content --> <p>Icon<span id="u92-2">iconsymbol</span></p> </div> 
Yes and it will be with all elements which has a title="icon"

 <script> $( document ).ready(function() { $("[title*='icon']").attr('data-attr',function(){ // I don't know }).removeAttr('title'); }); </script> 

Do you know how to do it? So I know it is very simple but I am new in jquery and I need in your help.
I hope you understood my question.

Here is an example that should work for you. There is probably a few ways you can pull this off, but this should hopefully get you started. Please see the attached JSFiddle to see this example in action

$(function() {
    $('[title*="icon"] span').each(function(){
        $(this).parent().closest('div').attr('data-attr', $(this).text())
    });
});

Here is another way you can do this as well

$('[title*="icon"]').each(function(){
    $(this).attr('data-attr', $(this).children().closest('span').text());
});

JSFiddle Example

Your <div> s should have attribute title="icon"

You are using a callback to attr() function, so return the value which you need to set inside the function using .text() .

$(document).ready(function () {
    $("[title='icon']").attr('data-attr', function () {
        return $(this).find('span').text();
    }).removeAttr('title');
});

Demo

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