I can use one variable in addClass/removeClass
html:
<body>
<p>Hello</p>
<p>and</p>
<p>Goodbye</p>
</body>
css:
p {
margin: 8px;
font-size: 16px;
}
.selected {
color: red;
}
.highlights {
background: yellow;
}
js:
var css1="selected";
var css2="highlights";
$( "p:last" ).addClass(css1);
I want use css1 and css2 variables in addClass method. I tried these:
$( "p:last" ).addClass(css1 css2);
$( "p:last" ).addClass("css1 css2");
They don't work.
If I use this:
var css3="selected highlights"
$( "p:last" ).addClass(css3);
it works
But how can I use css1 and css2 variables in addClass method ?
You can try on http://jsfiddle.net/hasyo1qm/
Thanks.
As noted elsewhere, you need to create a white-space separated string from your variables; one means (as shown):
$( "p:last" ).addClass(css1 + ' ' + css2);
Another alternative, however, which is slightly easier to type, is to use Array.prototype.join():
$( "p:last" ).addClass([css1, css2].join(' '));
JS Fiddle demo.
This, realistically, only becomes easier when you have more than two, or three, classes to concatenate.
References:
Array.prototype.join().
This works:
$( "p:last" ).addClass(css1+" "+ css2);
Both class names need a space between them, so using concatenation we have to add a space between them, otherwise it will not behave right.
UPDATED FIDDLE:
http://jsfiddle.net/ehsansajjad465/hasyo1qm/2/
You need to concatenate your variables:
$( "p:last" ).addClass(css1 + ' ' + css2);
updated jsFiddle
Try
var css1 = " selected "; // added space before and after text in string
var css2 = " highlights "; // added space before and after text in string
$( "p:last" ).addClass(css1 + css2);
http://jsfiddle.net/hasyo1qm/4/
Simpliest way is to call addClass multiple times but in one line:
$('p:last').addClass(css1).addClass(css2);
Related
As I'm making a style template for a website, I'd like to make span elements that from example blocks with a background color. Example:
<span class='colblock'>#FF0000</span>
should result in a block with color code #FF0000 (Red) as background color.
Currently, the following css and JS code is being used (relevant bits)CSS
<style>
span.colblock{
margin:8px;
padding:8px;
display:block;
border:1px solid black;
border-radius:2px;
width:66px;
}
</style>
Javascript (On page bottom, just before body)
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
$("colblock").each(function() {
var ccode = $(this).html();
$(this).css("background-color", ccode);
});
</script>
IMO, this is supposed to work, but it does not. Can someone elighten me?
While selecting element by class use . operator. You have error here:
$(".colblock").each(function() {
^ //missed '.' dot
Use following:
$(".colblock").each(function() {
var ccode = $(this).html();
$(this).css("background-color", ccode);
});
In css also you having typo:
<span.colblock{
^ //===> should be removed
See working Example
Use $(this).text() instead of $(this).html()
$(".colblock").each(function() {
var ccode = $(this).text();
$(this).css("background-color", ccode);
});
And in your css <span.colblock should be like this: span.colblock
To select a class, you should use $(".ClassName"), here it will be $(".colblock").
$("colblock") will select elements with tag name "colblock".
Your jquery link seems dead.
src="//code.jquery.com/jquery-migrate-1.2.1.min.js"
This one works as I tested:
src="http://code.jquery.com/jquery-1.2.1.min.js"
Not using JQuery
var the_Span = document.getElementById("colblock");
var span_Text = the_Span.innerText;
the_Span.style.backgroundColor = span_Text;
I need to make "bold" the second column of this html table:
http://jsfiddle.net/beKC4/4/
How can I do using JQuery?
I tried this but is not working:
$("h3.ms-standardheader").children("td").text("<b>"+this.text()+"</b>")
you can also use css
see here http://jsfiddle.net/beKC4/6/
table tr td:nth-child(3){
font-weight:bold;
}
Use .html() instead
$(".ms-standardheader").closest('tr').find("td").html(function () {
return "<b>" + $(this).text() + "</b>"
});
Also, the selector is incorrect, you need to use closest, then find the <td>
DEMO
Or if you don't want ms-standardheader to also get <b> you can use siblings()
$(".ms-standardheader").closest('td').siblings("td").html(function () {
return "<b>" + $(this).text() + "</b>"
});
DEMO
You can use this. Create a css class and add this class with js using :nth-child(). Think is simplier.
css
.bold{
font-weight: bold;
}
js
$('table td:nth-child(3)').addClass('bold');
fiddle
http://jsfiddle.net/b4AwC/
I would use nthchild selector, if you want ever other one bold you can put in even or odd
I hope this help
$("tr td:nth-child(2)").css({"color":"red"});
$("tr td:nth-child(even)").css({"background":"grey"});
So, I want to take the content of a div in which I have several <br/>, and then pass it as a title attribute using jQuery tooltip widget. I want the lines to appear one beneath the other inside the tooltip. thx. the code so far is:
CSS
.Lines {
width: 125px;
height:20px;
overflow:auto;
}
JavaScript
$(function () {
$(document).tooltip();
$(".Lines").hover(function () {
IaTxt = $(this).html()
$(this).prop('title', IaTxt)
})
});
HTML
<div class="Lines">
First line.
<br/>Second line.
<br/>Third line!
<br/>Fourth line?
</div>
There's a pure CSS solution. Use \n for newlines, and add this CSS style:
.ui-tooltip {
white-space: pre-line;
}
You can also use pre or pre-wrap instead of pre-line, if you want to preserve whitespace.
See https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
just use the entity
for a linebreak in a title attribute.
This is my trick to do it with latest jquery / jqueryui (assuming all of the items you want to have tooltips have class 'jqtooltip', they have title tags, and the title has a pipe character for a line separator:
$('.jqtooltip').tooltip({
content: function(callback) {
callback($(this).prop('title').replace('|', '<br />'));
}
});
You can use the 'content' option of the tooltip widget. See also:
http://jqueryui.com/tooltip/#custom-content
Short example:
$(function() {
$( document ).tooltip({
content: function() {
return 'foo'
}
});
});
You could type your HTML directly into the Title attribute and then simply call the following:
$(document).tooltip({
content: function (callback) {
callback($(this).prop('title'));
}
});
This way your HTML is rendered instead of escaped and literally written.
better use this:
$(document).tooltip({
content: function () {
return $( this ).prop( 'title' ).replace( '|', '<br />' );
}
});
with function(callback) i had an issue with tooltips which wasn't close
I used this:
$("[title]").each(function(){
$(this).tooltip({ content: $(this).attr("title")});
});
It means all elements with a title attribute is going to use the jquery tooltip and the tooltip content will use the value of the title attribute.
The content allows html.
I went with a modified version of ScottRFrost's answer. The problem with his example is that .replace only replaces the first instance of the character in the string. Here is a modified version that will use the regex's /g (global) to modify all instances of the character in the entire string.
$('.jqtooltip').tooltip({
content: function (callback) {
callback($(this).prop('title').replace(new RegExp("\\|", "g"), '<br />'));
}
});
I want my site title to display in a unique font from the rest of the content every time it appears in a heading, for branding reasons. For simplicity, let's pretend my special font is Courier and my company is called SparklePony. So, a line like,
<h1 class="title">SparklePony Board of Directors</h1>
would show a headline with the word SparklePony in Courier and Board of Directors in my site default font, Arial. (Yes, I know this would be hideous.)
I've tried using a jQuery string replacement, but I don't want to replace the string, I just want to see it in Courier (adding a class to just that word, or something of the like.) Replacing SparklePony with <span class="sparkle-pony">SparklePony</span> caused the whole ugly string with tags and everything to show on my site, rather than adding the class.
Am I doing something wrong with my string replace, or is there a better way to style all occurrences of a string?
You can do it like this - specifying the selector you want - #('h1') or by class.
$('.title').html(function(i,v){
return v.replace(/SparklePony/g,'<span class="sparkle">SparklePony</span>');
});
http://jsfiddle.net/cQjsu/
Without seeing the code (which would be kinda important in questions like this), best guess is that you're using .text() instead of .html() which would parse the HTML correctly.
It could do with some tidying, but this may be a good starting point: http://jsfiddle.net/c24w/Fznh4/9/.
HTML
<div id="title">Highlight this blah blah HiGhLiGhT THIS blah</div>
<button id="clickme">Click to highlight text</button>
CSS
#title{
font-family: sans-serif;
font-size: 20pt;
margin: 30px 0;
}
span.highlight{
color: #09f;
font-weight: bold;
}
JavaScript
function highlightText(element, phrase, allOccurrences, caseSensitive){
var modifiers = (allOccurrences ? 'g' : '') + (caseSensitive ? '' : 'i');
var text = element.innerHTML;
element.innerHTML = text.replace(new RegExp(phrase, modifiers), function(match){
return '<span class="highlight">' + match + '</span>';
});
}
var button = document.getElementById('clickme');
var el = document.getElementById('title');
button.onclick = function(){
highlightText(el, 'highlight this', true, false);
button.onclick = null;
};
Try Something like that :
$.each($(".title"),function({
$(this).html($(this).html().replace("SparklePony","<span class='sparkle-pony'>SparklePony</span>"))
});
Nice and short:
var $body = $("body");
$body.html($body.html().replace(/SparklePony/ig, "<span class='cool'>SparklePony</span>"));
But keep in mind that $("body") is a very costly selector. You should consider a more precise parent target.
Demo here (fiddle)
Goal:
Using jQuery, I'm trying to replace all the occurrences of:
<code> ... </code>
with:
<pre> ... </pre>
My solution:
I got as far as the following,
$('code').replaceWith( "<pre>" + $('code').html() + "</pre>" );
The problem with my solution:
but the issues is that it's replacing everything between the (second, third, fourth, etc)"code" tags with the content between the first "code" tags.
e.g.
<code> A </code>
<code> B </code>
<code> C </code>
becomes
<pre> A </pre>
<pre> A </pre>
<pre> A </pre>
I think I need to use "this" and some sort of function but I'm afraid I'm still learning and don't really understand how to piece a solution together.
You can pass a function to .replaceWith [docs]:
$('code').replaceWith(function(){
return $("<pre />", {html: $(this).html()});
});
Inside the function, this refers to the currently processed code element.
DEMO
Update: There is no big performance difference, but in case the code elements have other HTML children, appending the children instead of serializing them feels to be more correct:
$('code').replaceWith(function(){
return $("<pre />").append($(this).contents());
});
This is much nicer:
$('code').contents().unwrap().wrap('<pre/>');
Though admittedly Felix Kling's solution is approximately twice as fast:
It's correct that you'll always obtain the first code's contents, because $('code').html() will always refer to the first element, wherever you use it.
Instead, you could use .each to iterate over all elements and change each one individually:
$('code').each(function() {
$(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );
// this function is executed for all 'code' elements, and
// 'this' refers to one element from the set of all 'code'
// elements each time it is called.
});
Try this:
$('code').each(function(){
$(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );
});
http://jsfiddle.net/mTGhV/
How about this?
$('code').each(function () {
$(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );
});
Building up on Felix's answer.
$('code').replaceWith(function() {
var replacement = $('<pre>').html($(this).html());
for (var i = 0; i < this.attributes.length; i++) {
replacement.attr(this.attributes[i].name, this.attributes[i].value);
}
return replacement;
});
This will reproduce the attributes of the code tags in the replacement pre tags.
Edit: This will replace even those code tags that are inside the innerHTML of other code tags.
function replace(thisWith, that) {
$(thisWith).replaceWith(function() {
var replacement = $('<' + that + '>').html($(this).html());
for (var i = 0; i < this.attributes.length; i++) {
replacement.attr(this.attributes[i].name, this.attributes[i].value);
}
return replacement;
});
if ($(thisWith).length>0) {
replace(thisWith, that);
}
}
replace('code','pre');
As of jQuery 1.4.2:
$('code').replaceWith(function(i,html) {
return $('<pre />').html(html);
});
You can then select the new elements:
$('pre').css('color','red');
Source: http://api.jquery.com/replaceWith/#comment-45493689
jsFiddle: http://jsfiddle.net/k2swf/16/
If you were using vanilla JavaScript you would:
Create the new element
Move the children of old element into the new element
Insert the new element before the old one
Remove the old element
Here is jQuery equivalent of this process:
$("code").each(function () {
$("<pre></pre>").append(this.childNodes).insertBefore(this);
$(this).remove();
});
Here is the jsperf URL:
http://jsperf.com/substituting-one-tag-for-another-with-jquery/7
PS: All solutions that use .html() or .innerHTML are destructive.
Another short & easy way:
$('code').wrapInner('<pre />').contents();
All answers given here assume (as the question example indicates) that there are no attributes in the tag. If the accepted answer is ran on this:
<code class='cls'>A</code>
if will be replaced with
<pre>A</pre>
What if you want to keep the attributes as well - which is what replacing a tag would mean... ? This is the solution:
$("code").each( function(){
var content = $( "<pre>" );
$.each( this.attributes, function(){
content.attr( this.name, this.value );
} );
$( this ).replaceWith( content );
} );
$('code').each(function(){
$(this).replaceWith( "<pre>" + $(this).html() + "</pre>" );
});
Best and clean way.
You could use jQuery's html function. Below is a sample the replaces a code tag with a pre tag while retaining all of the attributes of the code.
$('code').each(function() {
var temp=$(this).html();
temp=temp.replace("code","pre");
$(this).html(temp);
});
This could work with any set of html element tags that needed to be swapped while retaining all the attributes of the previous tag.
Made jquery plugin, maintaining attributes also.
$.fn.renameTag = function(replaceWithTag){
this.each(function(){
var outerHtml = this.outerHTML;
var tagName = $(this).prop("tagName");
var regexStart = new RegExp("^<"+tagName,"i");
var regexEnd = new RegExp("</"+tagName+">$","i")
outerHtml = outerHtml.replace(regexStart,"<"+replaceWithTag)
outerHtml = outerHtml.replace(regexEnd,"</"+replaceWithTag+">");
$(this).replaceWith(outerHtml);
});
return this;
}
Usage:
$('code').renameTag('pre')