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 />'));
}
});
Related
How to find and remove a specific text in a html file?
I already found a code, but I think it doesn't work if there are charkters like "/" or "()" in the HTML-File.
My HTML-Code
<label>Text 1 (Blue/White/Green)</label>
My Script
$("label").children().each(function() {
$(this).html($(this).html().replace(/'(Blue/White/Green)'/g,""));
});
You just need to escape the slashes (and parens) in the regex, as well as remove the apostrophes. Secondarily, you're looking for children that don't exist, as the text is not within a child node, but the content of the label node, so removing the .children() filter will make it work:
$("label").each(function() {
$(this).html($(this).html().replace(/\(Blue\/White\/Green\)/g,""));
});
If you aren't interested in using a regex, you can also use the replace method with a string instead, though as written this will only replace the first instance:
$("label").each(function() {
$(this).html($(this).html().replace('(Blue/White/Green)',""));
});
You've to escape the slashes / and parentheses () using the antislash \ and you should also remove the single quotes ' and .children() also :
$("label").each(function() {
$(this).html($(this).html().replace(/\(Blue\/White\/Green\)/g,""));
});
Hope this helps.
Working snippet :
$("label").each(function() {
$(this).html($(this).html().replace(/\(Blue\/White\/Green\)/g,""));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Text 1 (Blue/White/Green)</label>
You should remove the children(). you need to iterate on the label elements. not on its children
$("label").each(function() {
$(this).html($(this).html().replace(/\(Blue\/White\/Green\)/g,""));
});
this should work
https://jsfiddle.net/L4b2m3a5/1/
Here you go!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('label').each(function() {
var text = $(this).text();
$(this).text(text.replace('(Blue/White/Green)', 'NOTHING'));
});
});
</script>
</head>
<body>
<label>Text 1 (Blue/White/Green)</label>
</body>
$(":contains('text-to-remove')").contents().filter(function () {
return (this.nodeType == 3 && $.trim(this.nodeValue) == 'text-to-remove');
}).remove();
from another poster
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);
I have made a function here:
function locationOfVideo(){//Outputs video location div according to post text
var ytVideoDiv = '<div class="youtube-video"><div id="<?php echo $divName; ?>-video"></div></div>';
$j('#main .content:contains("<--video-->")').replace('<--video-->', ytVideoDiv);
}
I thought this would work, but I am sorely mistaken and a bit tired. Anyways, what am i doing wrong here?
replace is a plain js function to replace part of a string or similar, not to replace the content of a jQuery object.
If the goal is to replace all the content in the selected element, and if you're using the right selector, you could use html() and do :
$j('#main .content:contains("<--video-->")').html(ytVideoDiv);
or to replace just the string <--video--> :
$j('#main .content:contains("<--video-->")').html(function(i,html) {
return html.replace('<--video-->', ytVideoDiv)
});
FIDDLE
Don't use <--video--> in your html, change to some other like {video}.
Then do it with:
$('#main .content:contains("{video}")').replaceWith(function() {
return $(this).text().replace('{video}', ytVideoDiv);
});
$j('#main .content:contains("<!--video-->")').replace('<--video-->', ytVideoDiv);
should be:
var videoNode = $j('#main .content:contains("<!--video-->")');
videoNode.html(videonode.html().replace('<!--video-->', ytVideoDiv));
or:
$j('#main .content:contains("<!--video-->")').html(function(index, oldhtml) { return oldhtml.replace('<--video-->', ytVideoDiv); });
It's better to output elements with special tag like abbr, check out javascript template usabe like jquery-timeago:
<abbr class="timeago" title="2011-12-17T09:24:17Z">December 17, 2011</abbr>
replace:
$('abbr.timeago').timeago()
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')
When any <a> tag is clicked with the id="cnt" I want to set the border color of div#fancybox-content to #000. My attempt:
$(document).ready(function(){
$('a#cnt').click(function(){
$("#fancybox-content").css("border-color","#000");
});
});
This code does not work.
are you sure you meant "id of 'cnt'"? you said "When any a tag is clicked"... is there more than one?
Make sure you set the other border parameters as well
If there is more than one, use a class:
$().ready( function() {
$("a.cnt").click(function() {
$("#fancybox-content").css({"border-width":"1px", "border-style":"solid", "border-color":"#000"});
});
})
see - http://jsbin.com/avuxe3/3
If there really is one:
$().ready( function() {
$("#cnt").click(function() {
$("#fancybox-content").css({"border-width":"1px", "border-style":"solid", "border-color":"#000"});
});
})
enter code here
The trick is in which selector you use. If you have a single HTML element that has an ID, use the # selector. If there is more than one element, you should use a class rather than ID and use the . selector. Below are examples:
If you have a single A tag, with an id="cnt" then you would use:
$('a#cnt').click(function() {
$('#fancybox-content').css({"border":"solid 1px #000"});
});
If you have more than one anchor with the cnt notation, set it as class="cnt" and use:
$('a.cnt').click(function() {
$('#fancybox-content').css({"border":"solid 1px #000"});
});
Better yet, keep your styles in a stylesheet like this
.borderOn { border: solid 1px #000; }
And then toggle this class on (and off if you like) with your links' click events:
$('a.cnt').click(function() {
$('#fancybox-content').addClass('borderOn');
});