2

I have a dynamic class that starts with z-. How can I dynamically change z- into fa- onload?

From <a href="#" class="z-dynamic">Link</a>

to <a href="#" class="fa-dynamic">Link</a>

I only want to replace a part of the class, not the whole class.

3 Answers 3

2

You could use an attribute contains selector and call attr with a callback function to modify the attribute for each element. In my example, I use a the string replace method with a regular expression to ensure that all classes in the list that start with z- are replaced, and only those instances of that string. Then just wrap it in the jQuery document ready wrapper, and you are ready to go.

$(function(){
    //Select only the a tags with "z-" in the "class" attribute, and modify the attribute using a callback function.
    $('a[class*="z-"]').attr('class', function(index, attr) {
        //Return the updated string, being sure to only replace z- at the start of a class name.
        return attr.replace(/(^|\s)z-/g, 'fa-');
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1
$(document).ready(function(){
    var self = $("a.z-dynamic");
    self.attr("class", self.attr("class").replace("z-", "fa-"));
});

This will change

From <a href="#" class="z-dynamic">Link</a>

to <a href="#" class="fa-dynamic">Link</a>

5 Comments

I think the dynamic part is unknown.
@AlexanderO'Mara You means you think it is coming from a variable?
void, "dynamic" part keeps on changing so I only need the "z-" part. thanks
I'm new here so I need more "reputations" to upvote. Pls upvote my question instead for me to get more reputations :) thanks
You mark it as the correct answer please so as to not create trouble to other users.
0

If you have a reference to that node already, you could easily apply a little regex alongside .replace() to the className.

anchor.className = anchor.className.replace(/z-/, 'fa-');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.