$('#content').load(href + ' #content');
is it possible to load only the contents of #content instead of loading the whole <div id="contents"> so I can prevent having <div id="contents"><div id="contents"></div></div>?
I forgot to place wrappers on a lot of pages and it would save me some time if there's a workaround on this.
I think you can try
$('#content').load(href + ' #content > *');
Note: If #content has any text nodes as its children(not descendants) then it may not work(the text nodes may not get copied)
Demo: Fiddle
Another solution is to manually remove the second wrapper, if it exists like
$('#content').load('ajax.html' + ' #content', function () {
if ($(this).children('#content').length) {
$(this).contents().unwrap()
}
});
Demo: Fiddle
Why not stick them somewhere else first then move over what you want
$(document.createElement('div')).load(href + ' #content', function (e) {
var elms = this.firstChild.childNodes,
parent = document.getElementById('content');
while (elms.length) {
parent.appendChild(elms[0]);
}
});
The load() method is mostly used to load remote data..
You cannot have two elements with the same ID..
$( "#result" ).load( "page.html #desiredContent" );
The $.load function takes handler for when the request is complete (http://api.jquery.com/load/). So when you request the matched '#content' element from the other page, have the complete function only return the inner html. Something like:
$('#content').load(href + ' #content',function(data){ return data.html(); });
Related
I found a lot of info about this, but I haven't foundanything that could help me yet.
My problem is that I have got a div with its id and it supposes to be a container (#cont_seguim).
I have a menu on the right side which contains circles (made by css and filled with text), like following:
<div class="circle_menu b">
<div class="text_menu n">ECO</div>
</div>
where b and n are the format for background and text.
When I click a circle, this one must be added to the container (notice that each circle has got its own text), but I can't get that.
I made and array and used alert() to test that click works, and it does, but append() doesn't even work to print text, and I don't know why.
<script type="text/javascript">
var arrayS = new Array();
$(document).ready(function() {
$(".circulo_menu").click(function() {
var text = $(this).text();
alert("calling " + text);
$("#cont_seguim").append(text);
});
return text;
});
</script>
Thank you for your responses!
Your code seems to work fine (if you fix the different class name used in html vs script circulo_menu vs circle_menu)
Demo at http://jsfiddle.net/7jbUj/
To add the whole circle append the whole element and not its text by using .append(this)
$(".circle_menu").click(function() {
$("#cont_seguim").append(this);
});
Demo at http://jsfiddle.net/7jbUj/1/
To add a copy of the circle, so you can add multiple of them use the .clone() first..
$(".circle_menu").click(function() {
var clone = $(this).clone(false);
$("#cont_seguim").append(clone);
});
Demo at http://jsfiddle.net/7jbUj/3/
Inside the click handler, this refers to the clicked element. And since you bind the click handler on the circle_menu element, this refers to that. You can use it directly for the appending or clone it to make a copy first..
unable to understand properly, hope below one can help you.
<script type="text/javascript">
$(document).ready(function() {
$(".circulo_menu").click(function() {
var myText = $(this).html();
alert("calling " + myText);
$("#cont_seguim").html(myText);
});
});
</script>
make sure classname and id name will remain same as html
Try using html() instead of text().
Try this: Demo
HTML:
<div class="circle_menu b">
<div class="text_menu n">ECO</div>
</div>
<div id="cont_seguim"></div>
Javascript:
$(document).ready(function() {
$(".circle_menu").click(function() {
var text = $(this).html();
console.log("calling " + text);
$("#cont_seguim").append(text);
});
});
Try this:
$( ".container" ).append( $( "<div>" ) );
source
use
$("#container").append($("<div/>", {id:"newID",text:"sometext"}));
You could try
<script type="text/javascript">
var arrayS = new Array();
$(document).ready(function() {
$(".circulo_menu").click(function() {
var text = $(this).text();
alert("calling " + text);
$("#cont_seguim").append($(this).html());
});
return text;
});
</script>
By this way the clicked circle element get added to div
I am trying to do something different without knowing if it is a good idea or not
I have a navigation menu as the following:
...
<li>Home</li>
<li>FAQ</li>
<li>Contact</li>
...
I do not want to use a server-side scripting because it takes more time to make db connection and define some configuration, and not want to multiply the pages for each one. So I made a master page index.php
in body section
there are two elements:
an h3 element to display the page title and a div to display the content which is called from another html source.
...
<div class="container">
<h3 id="pageTitle"></h3>
<div id="pageContent"></div>
</div>
...
I am using jQuery's click event to load the page into the div
$(function() {
$("a[href^='#m']").click(
function() {
$("#pageTitle").text($(this).text());
$("#pageContent").load($(this).attr("href").substring(1) + ".html"); //removing # char.
});
});
It works fine. But when I press F5 it returns the initial state as normal. How can I load the current page by referencing the address bar (I can see eg. sitename/#mfaq) when page is refreshed.
I think, first I need to detect if page is refreshing and load the corresponding html file in according to the #m**** on the addressbar.
$(function() {
$("a[href^='#m']").click( function(evt) {
// ------ This should work
// renamed parameter elem to evt like corrected in comment
evt.preventDefault();
$("#pageTitle").text($(this).text());
$("#pageContent").load($(this).attr("href").substring(1) + ".html");
});
});
Add to your DOM ready function:
if (window.location.hash != "") {
$("#pageTitle").text($("a[href='"+window.location.hash+"']").text());
$("#pageContent").load(window.location.hash.slice(1) + ".html");
}
I have made this. It works well. But I am not sure about performance issues:
$(function() {
var address = $(location).attr('href');
var hash = address.lastIndexOf("#");
var page = address.substring(hash+1);
if (hash < 1)
{
$("#pageContent").load("mhome.html");
$("#pageTitle").html("Default Page Title");
}
else
{
$("#pageContent").load(page + ".html");
$("#pageTitle").html($("a[href='" + address.substring(hash) + "']").text());
}
$("a[href^='#m']").click(
function() {
$("#pageTitle").text($(this).text());
$("#pageContent").load($(this).attr("href").substring(1) + ".html");
});
});
I'm loading in separate .html documents inside divs with this code:
JS
$('.thumbnail').click(function() {
var idStr = ("project/"+$(this).attr('id')) + " #projectcontainer";
$('#projectcontainer').animate({opacity:0});
$('#projectcontainer').hide().load(idStr,function(){
$(this).slideDown(500).animate({opacity:1}, function() {
$.scrollTo('#gohere',800);
$('#close').fadeIn(500).css({'display': 'block', 'height': '25px'});
});
});
});
HTML
<div class="thumbnail" id="atmotype.html">
<img src="image.whatever">
</div>
It all works as intended but I also wanna append an ID when you open a project, and also be able to link directly to said content (already expanded in the div). I've been trying around and can't come up with a solution, and that being said I'm pretty awful with JS in general.
Would really appreciate if someone could enlighten me on how this works.
Right now when you click your .thumbnail element, it is firing your click() event and using $(this).attr('id') for the hash/scroll. To make this run when the page load, you should probably break it out to a separate function that takes the ID as a parameter, and then call this function from your click() event as well as a generic page load using a parameter in location.hash.
$(document).ready(function(){
if (location.hash.length>0){
/* this assumes the page to load is the only thing in the
hash, for example /page.php#project.html */
var hash = location.hash.substring(1); // get hash and remove #
addHashAndScroll(hash); // call function with page name
}
$('.thumbnail').click(function() {
addHashAndScroll($(this).attr('id')); // pass ID value to function
});
}
// this function contains most of your original script
function addHashAndScroll(id){
var idStr = "project/"+ id + "#projectcontainer";
// rest of your code
}
UPDATE:
This is the thing about js it all makes sense when explained but executing it is a bitch. Anyways thanks alot for helping out. Based on your explanation what I get is:
$(document).ready(function() {
if (location.hash.length > 0) {
/* this assumes the page to load is the only thing in the
hash, for example /page.php#project.html */
var hash = location.hash.substring(1); // get hash and remove #
addHashAndScroll(hash); // call function with page name
}
$('.thumbnail').click(function() {
addHashAndScroll($(this).attr('id')); // pass ID value to function
});
}
// this function contains most of your original script
function addHashAndScroll(id) {
var idStr = "project/" + id + "#projectcontainer";
$('#projectcontainer').animate({
opacity: 0
});
$('#projectcontainer').hide().load(idStr, function() {
$(this).slideDown(500).animate({
opacity: 1
}, function() {
$.scrollTo('#gohere', 800);
$('#close').fadeIn(500).css({
'display': 'block',
'height': '25px'
});
});
});
}
I've tried to fiddle around with the closures and whatever minimal experience i have in bug testing js but i keep getting errors originating from this line:
function addHashAndScroll(id) {
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')
Lets say i have this:
$('a').each(function() {
$(this).click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
$('#somediv').load(href + ' #foo');
});
});
Now how would I make it load the inner contents of #foo and not the actual div #foo
Still not quite sure what I mean?
<div id="foo">
<!-- Load these divs only -->
<div class="children">bar</div>
<div class="children">bar</div>
<div class="children">bar</div>
<div class="children">bar</div>
<div class="children">bar</div>
<!-- // -->
</div>
I want to load the inner contents of a div only. Any help is greatly appreciated!
EDIT: SOLVED
I used the unwrap method:
parent.load(href + ' #' + ident + '', function() {
$('#'+ident+' > div').children().unwrap();
});
You can do this fairly easily if you don't mind using $.get and doing the loading parts by hand, something like this:
$.get(href, function(html) {
$('#somediv').html(
$(html).find('#foo').html()
);
});
This grabs the full chunk of HTML from href using $.get and then, in the success callback, we find the id="foo" element inside the whole pile of HTML, extract its content with .html() and then copy thing into #somediv with the mutator form of .html().
If you know that #foo will only contain <div> children, then you could try this:
$('#somediv').load(href + ' #foo > div');
I'm not certain that this will work and I don't have a decent test case set up but the .load documentation indicates that it should work. If #foo doesn't contain only <div>s then you'll have to come up with something else to use with the child selector (>). Of course, if #foo contains text that isn't wrapped in an element, then I think you're stuck with the $.get approach above.
You can load only the children of the anchor by using the > selector followed by an asterisk:
$('#somediv').load(href + ' #foo > *');
You can try this:
$(this).click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
$('#somediv').load(href + '#foo *',
function() {
$('#somediv #foo').remove();
});
});