Jquery : Adding class to dynamically generated li - javascript

i am using lightwidget to embed instagram feed.
When feed is inserted i want to add col-xs-6 class to each li element. i can get li elements by going to inspect element only.
this is the class that i am targeting
<li class="lightwidget__tile">
this is what i wrote
$('li.lightwidget__tile').each(function(){
$(this).addClass('col-xs-6');
})
this one does not add class to li elements ,
can someone help me if i am doing it right
Edit :
This is how code is being inserted
<iframe src="//lightwidget.com/widgets/address.html" scrolling="no" allowtransparency="true" class="lightwidget-widget" style="width: 100%; border: 0; overflow: hidden;"></iframe>

What you intend to do is not possible. iframes must abide by Same Origin Policy which means you need to have admin privileges to the website that resides in the iframe, or the site has a service that specifically allows you to access and manipulate the content of the page within the iframe. I took a quick look and didn't find any API documentation so unless you own https://lightwidget.com/ you will not be able to change classes of any element within the iframe.
The reason why you are able to change content inside the iframe with devtools is because that's by design. What you are able to do on an iframe with devtools is because the iframe context is different.
I suggest that you use the LightWidget Builder, it has a setting for columns.
Now if I'm wrong...
...and you actually do own lightwidget.com...
...or these list items are on your website either on the page like normal DOM...
...or on another page on your domain...
...then yes you should have no problem.
I believe option 2 was fully covered and even your original code would've worked. So we can forget about number 2 and let's assume number 1 is not true
...and you actually do own lightwidget.com...
...or these list items are on your website either on the page like normal DOM...
...or on another page on your domain...
Number 3 is very plausible, but a moot point because LightWidget and their services are accessed through their website exclusively.

Try This One
$('li.lightwidget__tile').each(function(){
$(this).append('<div class="col-xs-6"></div>');
})

Try using the arguments passed to each by jQuery:
$('li.lightwidget__tile').each(function(i, e){
// i is a counter of the loop element
$(e).addClass('col-xs-6');
})
As you say, your li is dynamically generated, try to wait a bit for the DOM to be updated, for example using setTimeout :
setTimeout(function(){
$('li.lightwidget__tile').each(function(i, e){
// i is a counter of the loop element
$(e).addClass('col-xs-6');
})
}, 250)
Update
In case you are trying to run jQuery inside iframe element, I recommend you to have a look to this and also this SO questions.

this is FUTURE elements matching the selector
$(document).on("DOMNodeInserted", "#li.lightwidget__tile", function() {
$(this).each(function(){
$(this).append('<div class="col-xs-6"></div>');
})
})
Hope this work.

To achieve this using iFrame, you must be able to apply jQuery to the external web content that is being retrieved via iFrame.
This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.
<div id='myframe'>
<?php
/*
Use below function to display final HTML inside this div
*/
//Display Frame
echo displayFrame();
?>
</div>
<?php
/*
Function to display frame from another domain
*/
function displayFrame()
{
$webUrl = 'http://[external-web-domain.com]/';
//Get HTML from the URL
$content = file_get_contents($webUrl);
//Add custom JS to returned HTML content
$customJS = "
<script>
/* Here I am writing a sample jQuery to hide the navigation menu
You can write your own jQuery for this content
*/
//Hide Navigation bar
jQuery(\".navbar.navbar-default\").hide();
</script>";
//Append Custom JS with HTML
$html = $content . $customJS;
//Return customized HTML
return $html;
}

Related

JavaScript DIV Editing Destroys Functionality of Other Elements

So my website is built using a company's software called Inksoft which leaves me very little to work in the way of customization. So I have to do many workarounds.
Here is my site's homepage.
The header on top of the page only has two links right now. "Products" and "Design Studio". My goal is to add an "About Us" link and "Buyers Guide" to the header as well.
I cannot add new content to the header using Inksoft's backend. So I coded a workaround to replace the content of existing DIV's within the header to say and link to where I want them to go.
The only issue is, the responsive mobile-nav loses functionality when this is implemented. As seen here on this test page.
The test page has the About Us in the top header, added by the use of this code:
<script>
$("#header-nav-designs").html('<document.write="<li id="header-nav-studio"><font color="#000000">About Us</font></li>');
</script>
So, the simplified question is: how do I implement this code without losing the responsive functionality of the nav bar?
The jQuery .html function will replace the HTML inside the target element. If you want to just append the one value, you likely want to .append to the element.
In addition, you aren't setting the HTML to a valid html string. You probably just want to get rid of the <document.write=" at the beginning of the string. The rest of it looks fine with just a cursory glance.
So:
<script>
$("#header-nav-designs").append('<li id="header-nav-studio"><font color="#000000">About Us</font></li>');
</script>
Edit:
After looking at it a little more, it appears as though the $('#header-nav-designs') that you are selecting is already an <li> which means you need to either select the parent <ul> list or you can use the jquery .after function instead.
<script>
$("#header-nav-designs").after('<li id="header-nav-studio"><font color="#000000">About Us</font></li>');
</script>
And as someone else commented above, you are getting an error on the page. It appears as though you are trying to get an element with the id divID and the appending some html to it, but there is no element with the id divID and so you are getting an error saying that you can't read the property innerHTML of null as the call to document.getElementById is returning null (element not found).
Element id header-nav-designs witch your code is referring have CSS style on line 170:
#header-nav-designs {display:none;}
The element will be hidden, and the page will be displayed as if the element is not there. With display:none;
If I understand you correctly your code selector points to wrong element id. It should point $(".header-nav > ul"). Document.write is not needed inside jQuery you need to give only an valid html string as argument.
jQuery html function erase html that is all ready inside element and replace it with html string given as argument. You have to use append if you want to add more html but not remove what is allready in element.
$(".header-nav > ul").append('<li><font color="#000000">About Us</font></li>');
$(".header-nav > ul").append('<li><font color="#000000">Buyers Guide</font></li>');

Dynamic iframe contents returns source, not parsed code

First question, so please correct me if this is in the wrong format.
I need to retrieve html for two dynamic elements from a dynamically created iframe, the below code returns "undefined". But I'm probably missing something really obvious.
$("#frame0").contents().find(elementID).html();
I am loading a same domain page into an iframe, two elements in the iframe are created from its jquery, the rest is static content in the iframe. The iframe is created and appended on a button click. The iframe in page looks and loads perfectly.
Below is the relevant code from within my button click:
$("#frameWrapper").append($('<iframe id="frame0" src="' + url + '"/>'));
$("#frame0").bind("load",function(){
var html = $(this).contents().find('#content').html();
var data = $(this).contents().find(elementID).html();
var table = $(this).contents().find(elementID).parent().find("table").html();
console.log(html);
console.log(data);
console.log(table);
});
#frameWrapper is a dynamically added container in the current page.
#frame0 is the actual iframe.
Of the three console.logs in the above code, html always returns the source code which is not the same as the actual view in the iframe on the page, data and table are always undefined, they are the two dynamic elements.
If I remove .html() from the above code, then all three elements are found and returned in the console.log.
I have tried too many things to list, as many answers on here as I can find, including checking all the suggested ones while I was writing this. But some of the ideas include, using plain javascript and adding a timeout to ensure load has completed, always the same response.
EDIT: Added the basic iframe code:
<div id="content">
<div class="wrap">
<div id="elementID"></div>
<table class="table"></table>
</div>
</div>
#elementID and .table are empty in the source and are only populated via a jquery function on load.
EDIT2: jsfiddle obviously it's having issues with Cross-domain policy so it's not really a good example, but it is a start.
Use this:
$("#frameWrapper").on("load", "#frame0", function () {
var html = $(this).contents().find('#content').html();
var data = $(this).contents().find(elementID).html();
var table = $(this).contents().find(elementID).parent().find("table").html();
console.log(html);
console.log(data);
console.log(table);
});
...instead of $("#frame0").bind("load",function(){...
This is called delegated events and should be used since the iframe is dynamically generated.
I don't have a working code to test for your issue, therefore the above is my guess to resolve your problem.

getting the contents of a div tag with class

I am trying to read the particular contents of an child IFrame wrapped in a div tag from parent window. I am using
detailsValue = window.frames['myIframe'].document.getElementById('result').innerHTML;
with this I'm able to access the entire content of that frame. But I need to access only a portion of that content. The problem is that the div which wraps the content that I am looking for contains only class and no ID.
<div class="watINeed"> <table class="details"> </table> </div>
I am unable to access the content which is in a form of table (with no id and only class).
Any help.
Edit1: I need to access the content of the table to check for char length and also for some html tags present in that content.
You can do this either using plain Javascript (as mentioned by Notulysses):
window.frames['myIframe'].document.querySelector('.watINeed .details')
or using jQuery (since you aded jquery) by specifying the iframe's document as context to $:
$(".watINeed .details", window.frames['myIframe'].document)
In the latter case you've a fullfeatured jQuery object.
Note that in either case the iframe's document has to be on the same domain otherwise you'd run into cross origin issues.
Tested against jQuery 2.0.x
Update
If you're running the selector during page load of the including page, you'll have to listen to the load event of the iframe before accessing its content:
$(window.frames['myIframe']).on("load", function(){
// above query here
});
If your are looking for a vanilla Javascript, and your target div is a direct children of starting selector, it is a simple task
var detailsValue = window.frames['myIframe'].document.getElementById('result').innerHTML;
var target;
for(var i = 0; i< detailsValue.children.lenght; i ++){
if(detailsValue.children[i].getAttribute('class')== 'watINeed'){
target = detailsValue.children[i] ;
}
}
otherwise, have to write a recursive method to scrap all children of structure
As i wrote above, it can be done using the following:
document.querySelectorAll(".className")[0] or $(".className")[0]
those are basically the same as both return a list of nodes and the [0] simply means taking the first result from the list.
there are 2 things to pay attention to:
the iframe loads the content asynchronously therefore when you execute the query its most likely that the elements you are searching for did not load yet.
executing the code after DOM loads is not enough.
the solution is simply put your code in a block that executes once all the asynchronous content is loaded:
window.onload=function(){
window.frames['myIframe'].document.querySelectorAll(".watINeed")[0];
}
or the jQuery alternative:
$(window).load(function(){
window.frames['myIframe'].document.querySelectorAll(".watINeed")[0];
});
the second thing is, according to the page Here, you can access the iframe's document using contentWindow.document:
window.onload=function(){
window.frames['myIframe'].contentWindow.document.querySelectorAll(".watINeed")[0];
}
or the jQuery alternative:
$(window).load(function(){
window.frames['myIframe'].contentWindow.document.querySelectorAll(".watINeed")[0];
});
live example: Fiddle

Static content in website

I've got a website and I'd like to make a part of it static. What happens is that the header, the menu bar and the footer are consistent in every page. I'd like to have them always loaded and when I click the menu button, it will only reload what is the body of the site.
Is there a simple chunck of code that can early achieve this? Something in js or ajax? I'm sorry but I don't have enough experience in these languages to accomplish something on my own. I've already tried to check jQuery library but it's still pretty confusing to me.
Thank you.
I think you don't even need Ajax or css!! Just use iFrames!! They are awesome, what happens is that u only design one page as the holder of your static content (Header-Menu ...) and put one iFrame in there as a place holder for any page you want to load in it, u should use proper css code to place the iFrame where you want, now, for every link in your menu, just set the "target" attribute equal to your iFrame's name and all the links will be loaded in that iFrame and your page won't be reloaded with every link click... I'll be back with some code...
Just add in every page a div container with ID for header, menubar and footer and just load it with this:
$(document).ready(function(){
$('#header').load('header.html');
$('#menubar').load('menubar.html');
$('#footer').load('footer.html');
});
Just make sure that the html files don't have html, head or body tags within, only the HTML-Code you would write inside the div. It's just like the include function in PHP.
EDIT:
For easy and simple implementation store the code above inside a .js file (e.g. include.js) and add this inside every head just below the include of all other scripts of your html files:
<script type="text/javascript" src="include.js"></script>
EDIT2:
Another solution ist to load the content of the page instead of the header, menubar, footer.
Here you take the same specifications (no html, body, etc. tags inside your content html files)
Name your content div e.g. <div id="content"></div>
Your navbar for example:
<div id="navbar">
Content1
Content2
</div>
JavaScript Code:
$(document).ready(function() {
//Click on a link that's child of the navbar
$('#navbar > a').click(function() {
//Get the html file (e.g. content1.html)
var file = $(this).attr('href');
//Load this file into the #content
$('#content').load(file);
return false;
});
});
You should consider the use of Server Side Included : http://httpd.apache.org/docs/current/howto/ssi.html
It's not quite easy to understand (as it refer to apache configuration), but this is a really great solution.
In a nutshell, you include parts of html code in you main page :
<!--#include virtual="/footer.html" -->
You won't have to use or understand all JQuery Framewol, user agent won't have to parse (if they are able to !) Javascript.
This is a pretty good replacement of PHP / ASP / Java for this kind of purpose.
You could use ajax to request the body of each page. But this is only one possibility - there are many. An other approach could be to create you page content using a script language (php, perl) serverside and employ a function there which adds footer, header and anything else to each page.
If you have an idea of Jquery then use click event on menu links to load the page in a div like the following syntax may help you.
$(document).ready(function(){
$("a.menu").click(function(){
$("#bodyContent").load("http://abc.com/your-linked-page.html");
});
});
To load the url dynamically use the following code:
In your menu bar the link looks like:
Home
In your Jquery code:
$(document).ready(function(){
$("a.menu").click(function(){
url = $(this).attr("title"); // here url is just a variable
$("#bodyContent").load(url);
});
});
Step 1: Add Jquery file into your html page.
Step 2: Use the above jquery code and change your menu link to the new what i said here.
Step 3: If you done it correctly, It will work for you.
How about a traditional iframe?
In your menu:
<a target="body" href="URL_to_your_Menu1_page">Menu1</a>
and then further in the document:
<iframe name="body" src="URL_to_homepage"></iframe>
You may use frameset and frames and organize you pages accordingly. So, frames containing menus can always be at display and while displaying contents on click of menu u may set target to frame in which you would like to load the contents.

Javascript Iframe innerHTML

Does anyone know how to get the HTML out of an IFRAME I have tried several different ways:
document.getElementById('iframe01').contentDocument.body.innerHTML
document.frames['iframe01'].document.body.innerHTML
document.getElementById('iframe01').contentWindow.document.body.innerHTML
etc
I think this is what you want:
window.frames['iframe01'].document.body.innerHTML
EDIT:
I have it on good authority that this won't work in Chrome and Firefox although it works perfectly in IE, which is where I tested it. In retrospect, that was a big mistake
This will work:
window.frames[0].document.body.innerHTML
I understand that this isn't exactly what was asked but don't want to delete the answer because I think it has a place.
I like #ravz's jquery answer below.
Having something like the following would work.
<iframe id = "testframe" onload = populateIframe(this.id);></iframe>
// The following function should be inside a script tag
function populateIframe(id) {
var text = "This is a Test"
var iframe = document.getElementById(id);
var doc;
if(iframe.contentDocument) {
doc = iframe.contentDocument;
} else {
doc = iframe.contentWindow.document;
}
doc.body.innerHTML = text;
}
If you take a look at JQuery, you can do something like:
<iframe id="my_iframe" ...></iframe>
$('#my_iframe').contents().find('html').html();
This is assuming that your iframe parent and child reside on the same server, due to the Same Origin Policy in Javascript.
Conroy's answer was right. In the case you need only stuff from body tag, just use:
$('#my_iframe').contents().find('body').html();
You can use the contentDocument or contentWindow property for that purpose.
Here is the sample code.
function gethtml() {
const x = document.getElementById("myframe")
const y = x.contentWindow || x.contentDocument
const z = y.document ? y.document : y
alert(z.body.innerHTML)
}
here, myframe is the id of your iframe.
Note: You can't extract the content out of an iframe from a src outside you domain.
Don't forget that you can not cross domains because of security.
So if this is the case, you should use JSON.
This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.
<div id='myframe'>
<?php
/*
Use below function to display final HTML inside this div
*/
//Display Frame
echo displayFrame();
?>
</div>
<?php
/*
Function to display frame from another domain
*/
function displayFrame()
{
$webUrl = 'http://[external-web-domain.com]/';
//Get HTML from the URL
$content = file_get_contents($webUrl);
//Add custom JS to returned HTML content
$customJS = "
<script>
/* Here I am writing a sample jQuery to hide the navigation menu
You can write your own jQuery for this content
*/
//Hide Navigation bar
jQuery(\".navbar\").hide();
</script>";
//Append Custom JS with HTML
$html = $content . $customJS;
//Return customized HTML
return $html;
}
document.getElementById('iframe01').outerHTML
You can get the source from another domain if you install the ForceCORS filter on Firefox. When you turn on this filter, it will bypass the security feature in the browser and your script will work even if you try to read another webpage. For example, you could open FoxNews.com in an iframe and then read its source. The reason modern web brwosers deny this ability by default is because if the other domain includes a piece of JavaScript and you're reading that and displaying it on your page, it could contain malicious code and pose a security threat. So, whenever you're displaying data from another domain on your page, you must beware of this real threat and implement a way to filter out all JavaScript code from your text before you're going to display it. Remember, when a supposed piece of raw text contains some code enclosed within script tags, they won't show up when you display it on your page, nevertheless they will run! So, realize this is a threat.
http://www-jo.se/f.pfleger/forcecors
You can get html out of an iframe using this code
iframe = document.getElementById('frame');
innerHtml = iframe.contentDocument.documentElement.innerHTML

Categories