setting color of a link in javascript - javascript

I want to set the color of "val" in the link in below code.
var link = $('' + val + '<br><br>');//this is the link
link.style.color="red";//this is how iam trying to set the color of "val"
SO HOW TO EXACTLY DO IT.

You can do this:
link.css({ color: 'red' });
But the correct and nice way would be:
$(".parent_element").prepend(''+val+'<br><br>');
$(".parent_element > a:first").css({ color: 'red' });

Try this:
$(link[0]).css({ color: 'red'});
The reason for this is that link is not an <a> element - it's a set of elements: <a>, <br> and another <br>.
Another approach would be:
link.css({ color: 'red' });
but this will set this CSS to not only <a>, but both <br>'s as well (not a big deal though).

If you are using jQuery(which it does seem like) go ahead with this,
jQuery
link.css("color","red");
Otherwise,
JavaScript
link[0].style.color = "red";
What you did doesn't work because link is an array. Before applying a style to it, you have to first select the first element by link[0] and then operate on it.

You could use link.style.color="red" if link was an HTMLElementNode, but it isn't. It might be a jQuery object, but if you are using an older version of the library then it will return undefined.
First you need to fix your jQuery call. You can't create multiple elements at the top level. (You can skip this bit if you are using a sufficiently new version of jQuery).
Since there is no good reason to use a double <br> (it shouts "Use CSS to add a margin instead"), I've taken them out:
var link = $('' + val + '');
Now you have a jQuery object so you can either use the jQuery method of setting CSS:
link.css("color", "red");
or get the HTMLElementNode from the jQuery object and use that:
link.get(0).style.color="red";

link.css("color", "red")
However, I think it would be better to create a css class for that and set up the color there. In Javascript/jQuery I would just add the class to the tag when needed. It is more elegant.

Related

How to change colour of text when using document.getElementById("id").innerHTML

I am trying to change the text of a span to something else when a particular event occurs. I am doing this as :
document.getElementById("usernameError").innerHTML = "**Message";
I want to display the same in a different colour. Any idea on how to do that?
Much appreciated!
You could always just put the message in a span and put a style attribute on it. This should do it:
document.getElementById("usernameError").innerHTML = "<span style='color: red;'>**Message</span>";
As you can find in the Mozilla Developer Network, you can use HTMLElement.style property to change any style on the element.
So you can do something like this to colour it in red:
document.getElementById("usernameError").style.color = '#d00'
A more future proof and reusable solution would probably be to add a class to either the current element or the span element, depending on your requirements:
document.getElementById("usernameError").className = "color-red";
Or working off Erics solution:
document.getElementById("usernameError").innerHTML = "<span class='color-red'>**Message</span>";
Then in your CSS:
.color-red{
color: #F00;
}
You could obviously also add diff colours and attribute in a much more maintainable way like this.
NOTE: className Returns A String, representing the class, or a space-separated list of classes, of an element.

How can I change a css style for 'this' class using jquery?

I have a list of images that each are tied to a class.
var hoverList = this.hoverable.getAllList() //this gets the list.
on mouseover of the images, I want a block of text in a different area, but shares a class, to display. I call
hoverList.mouseover(this.hoverable.displayTheDeets)
and it runs
displayTheDeets: function(){
big=$(".project-details")
thisClass=$(this).attr("class")
console.log(thisClass)
//$(big).find(thisClass).css("display","")
$(big).find(thisClass).css("display", "block")
//$(big > thisClass).css("display","block")
}
From the console, if I run the literal command
$(".project-details").find(".code-fusion")
it returns the element I want. And I can change the display with no problem.
I think my problem is with thisClass. Any thoughts would be appreciated.
Try,
big.find('.' + thisClass).css("display", "block");
or simply
big.find('.' + thisClass).show();
Please note that .attr('class') would return the class being used for the particular element, and it wont return the class name in the format of selector.
Additional Note: And in sometimes if you have more than one class set with that particular element then it would make the selector as invalid like $('.class1 class2 class3')
Try with prefix dot. the attr("class") returns only the name not the prefix dot.
$(big).find("."+ thisClass).css("display", "block")
or
$(big).find("."+ thisClass).show();
Try
$(big).find("."+ thisClass).css("display", "block")
Part of the problem has already been answered well enough; however, I would suggest that you solve this problem in another way.
You can define the class name separately from the class of your hovering element, e.g.
<... class="something" data-linked="theclass">
Then:
displayTheDeets: function(){
var className = $(this).data('linked');
$(".project-details").find('.' + className).show();
}

JQuery change color based of class based on HTML content

I am trying to use JQuery to get the inner html of a div (class box_bottom).
These div's are javascript generated, pulling from XML, therefore (dependant on the XML) there could be (and so I need to cater for) multiple occurrences, so cannot do this by ID. If the content is "notifications" then I want the color to be blue, and if the content is "VO" I want the color to be red
$.category = $('.box_bottom').innerHTML;
if ($.category == 'Notifications') {
$(".box_bottom").css("color", "blue");
}
if ($.category == 'VO')
{
$(".box_bottom").css("color", "red");
}
Chrome dev console is not showing any errors - I am unsure where I am going wrong.
Complete novice to JQuery so have just been googling syntax - so apologies if this is a super simple issue.
You can not access innerHTML property on jQuery object. You need to use html() instead of innerHTML
Change
$.category = $('.box_bottom').innerHTML;
To
$.category = $('.box_bottom').html();
OR
$.category = $('.box_bottom').text();
You may also need to use $.trim to avoid any extra space within text, and its better to use category instead of $.category as it defined category with $ jQuery object.
$.category = $.trim($('.box_bottom').text());
$.category = $('.box_bottom').text().trim();
if ($.category == 'Notifications') {
$(".box_bottom").css("color", "blue");
}
if ($.category == 'VO')
{
$(".box_bottom").css("color", "red");
}

jQuery replace one class with another

I have this jQuery and I'm changing styles in it but I've heard that the correct way to do it is to create a separate style and just replace classes with jQuery. Can you explain me how to do it correctly:
$('.corpo_buttons_asia').click(function() {
$('.info').css('visibility', 'hidden');
$('.info2').css('visibility', 'visible');
$(this).css('z-index', '20');
$(this).css('background-color', 'rgb(23,55,94)');
$(this).css('color', '#FFF');
$('.corpo_buttons_global').css('background-color', 'rgb(197,197,197)');
$('.corpo_buttons_global').css('color', '#383838');
});
$('.corpo_buttons_global').click(function() {
$('.info').css('visibility', 'visible');
$('.info2').css('visibility', 'hidden');
$(this).css('background-color', 'rgb(23,55,94)');
$(this).css('color', '#FFF');
$('.corpo_buttons_asia').css('z-index', '2');
$('.corpo_buttons_asia').css('background-color', 'rgb(197,197,197)');
$('.corpo_buttons_asia').css('color', '#383838');
});
So instead of using .css() all the time I can create another class and just replace it with jQuery.
To do this efficiently using jQuery, you can chain it like so:
$('.theClassThatsThereNow').addClass('newClassWithYourStyles').removeClass('theClassThatsTherenow');
For simplicities sake, you can also do it step by step like so (note assigning the jquery object to a var isnt necessary, but it feels safer in case you accidentally remove the class you're targeting before adding the new class and are directly accessing the dom node via its jquery selector like $('.theClassThatsThereNow')):
var el = $('.theClassThatsThereNow');
el.addClass('newClassWithYourStyles');
el.removeClass('theClassThatsThereNow');
Also (since there is a js tag), if you wanted to do it in vanilla js:
For modern browsers (See this to see which browsers I'm calling modern)
(assuming one element with class theClassThatsThereNow)
var el = document.querySelector('.theClassThatsThereNow');
el.classList.remove('theClassThatsThereNow');
el.classList.add('newClassWithYourStyleRules');
Or older browsers:
var el = document.getElementsByClassName('theClassThatsThereNow');
el.className = el.className.replace(/\s*theClassThatsThereNow\s*/, ' newClassWithYourStyleRules ');
You may use this simple plugin:
(function ($) {
$.fn.replaceClass = function (pFromClass, pToClass) {
return this.removeClass(pFromClass).addClass(pToClass);
};
}(jQuery));
Usage:
$('.divFoo').replaceClass('colored','blackAndWhite');
Before:
<div class="divFoo colored"></div>
After:
<div class="divFoo blackAndWhite"></div>
Note: you may use various space separated classes.
Sometimes when you have multiple classes and you really need to overwrite all of them, it's easiest to use jQuery's .attr() to overwrite the class attribute:
$('#myElement').attr('class', 'new-class1 new-class2 new-class3');
Starting with the HTML fragment:
<div class='helpTop ...
use the javaScript fragment:
$(...).toggleClass('helpTop').toggleClass('helpBottom');
In jquery to replace a class with another you can use jqueryUI SwitchClass option
$("#YourID").switchClass("old-class-here", "new-class-here");
You'd need to create a class with CSS -
.greenclass {color:green;}
Then you could add that to elements with
$('selector').addClass("greenclass");
and remove it with -
$('selector').removeClass("greenclass");
You can use .removeClass and .addClass. More in http://api.jquery.com.
You can use jQuery methods .hasClass(), .addClass(), and .removeClass() to manipulate which classes are applied to your elements. Just define different classes and add/remove them as necessary.
Create a class in your CSS file:
.active {
z-index: 20;
background: rgb(23,55,94)
color: #fff;
}
Then in your jQuery
$(this).addClass("active");
you could have both of them use a "corpo_button" class, or something like that, and then in $(".corpo_button").click(...) just call $(this).toggleClass("corpo_buttons_asia corpo_buttons_global");
jQuery.fn.replaceClass = function(sSearch, sReplace) {
return this.each(function() {
var s = (' ' + this.className + ' ').replace(
' ' + sSearch.trim() + ' ',
' ' + sReplace.trim() + ' '
);
this.className = s.substr(1, s.length - 2);
});
};
EDIT
This is my solution to replace one class with another (the jQuery way). Actually the other answers don't replace one class with another but add one class and remove another which technically is not the same at all.
Here is an example:
Markup before: <br class="el search-replace"><br class="el dont-search-replace">
js: jQuery('.el').remove('search-replace').add('replaced')
Markup after: <br class="el replaced"><br class="el dont-search-replace replaced">
With my solution
js: jQuery('.el').replaceClass('search-replace', 'replaced')
Markup after: <br class="el replaced"><br class="el dont-search-replace">
Imagine a string replace function in whatever language:
Search: "search-replace"
Replace: "replaced"
Subject: "dont-search-replace"
Result: "dont-search-replace"
Result (wrong but actually what the other solutions produce): "dont-search-replace replaced"
PS
If it's for sure that the class to add is not present and the class to remove is present for sure the most simple jQuery solution would be: jQuery('el').toggleClass('is-present-will-be-removed is-not-present-will-be-added')
PPS I'm totally aware that if your selector equals the class to remove the other solutions would work just fine jQuery('.search-replace').removeClass('search-replace').addClass('whatever').
But sometimes you work with more arbitrary collections.
I have used swap div to swap my video of self in thumbnail to main-video and vise versa.
I think this will help you to make a toggle between two div class.
numberId=0
function swapVideo(){
numberId++;
console.log(numberId)
if(numberId % 2 ==0){
$('#self-video').attr('class', 'main-video');
$('#trainer-video').attr('class', 'thumb-video');
}else{
$('#self-video').attr('class', 'thumb-video');
$('#trainer-video').attr('class', 'main-video');
}
}
numberId%2==0 help to keep track and perform a operation to make this toggle.

Remove tag around a text node using javascript

If I have some HTML that looks like this:
<div id="text">
This is some text that is being written <span class="highlight">with
a highlighted section</span> and some text following it.
</div>
And I want to remove the "span" leaving the text node within, how would I go about doing that? I tried using jQuery to do the following:
wrap = $('.highlight');
wrap.children().insertBefore(wrap);
wrap.remove();
But that doesn't work I'm guessing because children returns an empty set since there's only a text node in there. So all that happens is that the span and its contents are removed.
I'm also open to alternatives to my approach here. What's happening is that my code actually creates that span when a user selects a block of text. It wraps the selected text in a span to visually differentiate it. I need to remove the span afterward though because of some quirks with the way mozilla's range object works.
EDIT: I don't want to replace the entire content of '#text' by the way since it could be very large.
You get the text, and replace the span with it:
var wrap = $('.highlight');
var text = wrap.text();
wrap.replaceWith(text);
wrap it in a plugin
(function($) {
$.fn.tagRemover = function() {
return this.each(function() {
var $this = $(this);
var text = $this.text();
$this.replaceWith(text);
});
}
})(jQuery);
and then use like so
$('div span').tagRemover();
Working Demo here - add /edit to the URL to play with the code
This works:
wrap = $('.highlight');
wrap.before(wrap.text());
wrap.remove();
This will do what you want, and also preserve any tags within the .highlight span.
content = $(".highlight").contents();
$(".highlight").replaceWith(content);
element = document.getElementById("span id");
element.parentNode.insertBefore(element.firstChild, element);
element.parentNode.removeChild(element);
text.replace(/</?[^>]+(>|$)/g, "");
it would be much easier to just change the class of the span than to actually remove it. You can use pure javascript:
document.getElementById("span id").className="";
Or jquery's toggleClass function:
$("element").toggleClass("highlight");
Also, best practices say that you shouldn't use class names that imply a style, like highlight. Try "emphasized" instead. :D
A better unwrap plugin:
$.fn.unwrap = function() {
this.parent(':not(body)')
.each(function(){
$(this).replaceWith( this.childNodes );
});
return this;
};
from Ben Alman

Categories