How to dynamically replace part of a class using jQuery? - javascript

I have a dynamic class that starts with z-. How can I dynamically change z- into fa- onload?
From Link
to Link
I only want to replace a part of the class, not the whole class.

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-');
});
});

$(document).ready(function(){
var self = $("a.z-dynamic");
self.attr("class", self.attr("class").replace("z-", "fa-"));
});
This will change
From Link
to Link

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

Related

Unable to replace the class of div element - no method named css

I want to replace the old class of html element with the new one using jQuery. Here is what I'm doing:
var elem = $('.my_selector')[0];
elem.css('class', 'my_new_class');
But I get the error saying "Uncaught type error: Object#<HtmlDivElement> has no method css.
How do I fix it?
The problem is that you are trying to call jQuery method css() (even not relevant here) from DOM element, which is derived with [0]. You can use toggleClass() to do the job:
$(".my_selector:first").toggleClass("my_selector my_new_class");
$('.my_selector')[0] is returning you a DOM element, not a jQuery Object. You'll also want to use the addClass method rather than css. To get the first element, you can use the :first pseudoselector.
So this should be what you are looking for:
$('.my_selector:first').removeClass('my_selector').addClass('my_new_class');
EDIT You can use either removeClass/addClass or toggleClass. Either are fine. Explicitly adding the new class may be safer if you have a case where an element can have both classes at the same time since toggleClass will remove both classes.
var elem = $('.my_selector')[0];
This will return the DOM element, not a jQuery object. Simply change it to this...
var elem = $('.my_selector');
To get just the first element that matches the selector, use this...
var elem = $('.my_selector').first();
Also, you have...
elem.css('class', 'my_new_class');
This is incorrect and should be changed to this...
elem.attr('class', 'my_new_class');
Try this ,
var elem = $(".my_selector");
elem.class("newclass");
otherwise you can do,
var elem = $(".my_selector");
elem.removeClass("my_selector");
elem.addClass("newclass");
$(".my_selector").removeClass('currentClass').addClass('newClass');
As said, you need the jquery object of the first element. A good method could be this:
$('.my_selector').first().css('class', 'my_new_class');
Moreover the method signature is .css( propertyName, value ) so its intented to set a css property not to change a class. To do that you need to remove old class and add new one with .removeClass and .addClass respectively.
$($('.my_selector')[0]).css('class', 'my_new_class');
document.getElementsByClassName('my_selector')[0].className = 'my_new_class';

Using remove as opposite of append not working

Here's how I append the value:
$('<div>someText</div>').appendTo(self);
And here's how I want to remove it:
$(self).remove('<div>someText</div>');
The appending works, the removing doesnt. What am I doing wrong?
The .remove() function takes a selector to filter the already matched elements, not to match elements inside of them. What you want is something like this:
$(self).find('div:contains(someText)').remove();
That will find a <div> element containing the text someText inside of whatever element self is, then removes it.
The API http://api.jquery.com/remove/ sais that a selector is required.
Try $(self).remove('> div');
This will remove the first childs of div.
You can use $(self).filter('div:contains("someText")').remove(); to remove a div with a specific content or $(self).find('> div').remove(); to remove the first childs of div.
EDIT: removed first version I posted without testing.
It most likely has to do with the scope of self. Since you've named it self I am assuming that you are getting this variable using $(this) on the click event. If that's the case, and you want to call the remove method, you can only do so from within the same function. Otherwise you need to either store the element in a variable or provide another selector to access it.
Example:
<div class="div1"></div>
this will be the div with the click event
$(document).ready(function(){
var self = null;
$('.div1').click(function(e){
self = $(this);
var itemToAdd = '<div>SomeText</div>';
$(itemToAdd).appendTo(self);
});
// to remove it
// this will remove the text immediately after it's placed
// this call needs to be wrapped in a function called on another event
$('.div1').find('div:contains(someText)').remove();
});

jquery hasClass, can it be given the beginning of class name, to get the full class name

I'm trying to do something similar to this question, but it's a bit different, so the solution there isn't working for me.
<span class="a-class another-class test-top-left"></span>
I have an element (this code shows a span but it could be div span or anything). This element has a class beginning with test- (test-top-left, test-top-right etc.) I've triggered a click event on classes starting with test- and saved the clicked object as var object = this;. Simple stuff so far.
What I'm trying to do now is get the full name of that class (test-top-left). I know it starts with test- but what's the full name. The thing is that there are other classes a-class another-class and test-top-left. Can hasClass be used to get the full name of the class? I'd prefer not to use find() or filter() just because there may be additional elements within that also have class="test-"
Edit:
The code I have now is, but it gives me ALL the classes. What I need is the single class beginning with test-.
var object = this;
$(object).attr('class');
So now I for loop through all the classes and test each one separately, which seems like a lot of unnecessary code. I'm hoping jQuery has a clever way to get the exact class that was clicked right away.
Description
You can use jQuerys Attribute Contains Selector, .attr() and .click() method.
Attribute Contains Selector - Selects elements that have the specified attribute with a value containing the a given substring.
.attr() - Get the value of an attribute for the first element in the set of matched elements.
.click() - Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
Sample
html
<span class="anyclass test-hello">Hello World</span>​
jQuery
$("[class*='test']").click(function() {
var object = $(this);
alert(object.attr("class").match(/(test-.*?)(?:\s+|$)/)[1])
;});
Check out the updated jsFiddle
Update
If you dont want to use regex you can do this.
$("[class*='test']").click(function() {
var object = $(this);
alert("test-" + object.attr("class").split("test-")[1].split("-"))
;});
​
More Information
jQuery - Attribute Contains Selector
jQuery - .attr()
jQuery - .click()
jsFiddle Demonstration
This should work for you:
var object = this;
var className = object.className.match(/(test-.*?)(?:\s+|$)/)[1];
Class name is the name of the class you are looking for.
If you don't want to use split or regex, you can try having the class in a separate attribute
<span class="someclass test-something" _rel="test-something">test<span>
or
<span class="someclass" _rel="test-something">test<span>
with the script
$("[_rel*='test-']").click(....
And to retrieve the attribute, use $(this).attr("_rel")

Using jquery 1.4 or javascript how would I target a specific link using a variable

HTML:
I've attached a simplified example of the problem I'm facing:
<h2>Product2</h2>
<div id="products">
<a class="my-product1" href="#"><span>my-product1<span></a>
<a class="my-product2" href="#"><span>my-product2<span></a>
<a class="my-product3" href="#"><span>my-product3<span></a>
<a class="my-product4" href="#"><span>my-product4<span></a>
<a class="my-product5" href="#"><span>my-product5<span></a>
</div>​
Javascript:
I'm already pulling myProduct from the page title and forcing lowercase. Next I'm attempting to remove this product from the group of links based on its class. Its quite possible this is jquery101 however I can't figure out how to add a class to a link using a variable to determine which class to select. In this example lets assume var myProduct = Product2
function removeProduct(myProduct){
$("a.myProduct").addClass("display-none");
};
Also, I am still learning so if you have the time a Brief explination of why what i'm doing is wrong would go a long way. Thanks for your time!
Simply concat the class name to the selector string:
$("a."+variable)...
Extra info as you requested:
Don't use a class "display-none"... change it's name or use jQuery native code that hides elements(hide(docs))
function removeProduct(myProduct){
$("a." + myProduct).hide();
};
Changing css rules is with the css(docs) function:
function removeProduct(myProduct){
$("a." + myProduct).css('display', 'none');
};
Adding class is with addClass function:
function removeProduct(myProduct){
$("a." + myProduct).addClass('someClass');
};
Change myProduct and removeProduct names to more meaningful variable names:
function hideAnchorElement(className){
$("a." + className).hide();
}
The class attribute / property is used as a generic selector - ie you can apply a class to multiple objects ... the id attribute / property is used for specific selection - and are unique. I suggest you change your HTML to use ids instead of classs
Try something like :
function removeProduct(myProduct){
$("a."+myProduct).css("display","none");
};
uses .css() to change the display property to none
or
function removeProduct(myProduct){
$("a."+myProduct).hide();
};
.hide() does the same thing as the .css() method does above
or
function removeProduct(myProduct){
$("a."+myProduct).addClass("yourclass");
};
where yourclass is a class you want to apply to an element.
And may I suggest you take a look at How jQuery works
Are you looking for this:
function removeProduct(myProduct){
$("a."+myProduct).addClass("display-none");
};
Separating the string selector from the variable
Try this if you want to hide the link on click event
$(function(){
$('#products a').on('click', function(e){
e.preventDefault();
$(this).hide();
});
});​
A fiddle is here.

How can I alter the `href` attribute of an anchor using jQuery

I have a link:
MyLink
What I need to do with jQuery to edit the href attribute?
If you want to modify the displayed anchor text, use .text()
$('a').text(function(_, currentText) {
return 'Here ' + text
});
That would change the line into
Here MyLink
If you want to modify the linked href, use .attr()
$('a').attr('href', 'your new value');
You can use the .attr() the same way I demonstrated with .text() above (passing a function and access the current value also)
Ref.: .attr(), .text()
Easy
$('a').attr('href','yourTextHere');
Yes
$("a").attr('href', 'value');
Might be a good idea to set an ID on the element to specifically target it:
$("a#id").attr('href', 'value');
This should do it.
$("#id").attr("href", "Etc");
.attr()
First add a class name to that link, as shown below.
MyLink
Then,
$('.classname').attr('href','insert link here');
If you're wanting to change the text of the link then:
$('a').text('My link text');
If it's the href you want to change, then, as noted by others it's:
$('a').attr('href','newURL');
If you're okay using plain JavaScript:
var a = document.getElementById('aElementID');
a.innerHTML = 'My Link Text';
a.href = 'http://new.link.com/path/to/page.html';
Note that you'll need some way to uniquely identify the particular a element you want to target, either using an id (to give $('#aElementID')) or a class (to give $('a.className'), though this will return a node list/array of elements that you'll then have to iterate through).
you can attach it as by specifying the id to it and then uniquely accessing the anchor tag by the classname
;
$("a.mylink").attr('href', 'http://google.com');

Categories

Resources