JQuery accessing PHP generated content - javascript

I have
<?php
include('print.php')
?>
That echoes html code inside my document, and after I load it I can't access the divs by id with jQuery
$("#"+divId)
It doesn't work even from chrome's console.
I can access them with plain javascript
document.getElementById(divId)
If I hardcode the divs I can access them via jQuery.
Can anyone explain me why php-generated code is not accessible via jQuery?

You need to use $('#' + divId) inside your document load. It does not work from chrome's console because variable divId does not exist.
Try this:
$(function() {
var divId = Whatever your Div ID is;
var div = $('#' + divId);
});

In the end it proved to be a stuipid distraction, The fact that the content was dynamically generated on the server side was totally incidental. One of the divs contained a dot instead of a dash in the id ('#1.0'), so jquery was interpreting it as '#[id].[class]'

Related

Jquery : Adding class to dynamically generated li

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;
}

Replacing contents of html page using another html page

I am trying to avoid header, sidebar info repeating of my html page template.
So, I was thinking to user innerHTML to replace the contents on the fly. However, I do not want to put entire target html on the same page under innerHTML as it will be nightmare to debug or maintain later.
So, is there a way to specify the another page link in the innerHtml and have contents separate?
just as an example
<script type="text/javascript">
function replacePage(page){
var ele = document.getElementById('page-wrapper'); ele.innerHTML = "<div>hey vik</div>";
}
</script>
I'm looking if i can specify the innerHTML value as some .html file name and move the <div>hey vik</div> there.
ok guys i finally used jquery to do this. What I did was instead of loaded content part, i actually moved the static part into a .html file and then loaded it via jquery as
$(function() {
$("#includedContent").load("navbar.html");
};
the place where i need to rander it i added as below
<div id="includedContent"></div>
You can use document.documentElement to select the root element of the document and the store it in a variable:
let content = document.documentElement;
And then use innerHTML to change the page content:
content.innerHTML = "<body><h1>text</h1><body>";

Javascript Variable in Url.Content

I have a javascript variable called locid that I am trying to use as part of a URL by setting the data-url of a div as follows:
data-url='#Url.Content("~/Catalogue_Items/ItemsActionViewPartial/")#Model.CatItemID?LocationID=locid&AsyncUpdateID=catalogue-view'>
I know I can't just throw the locid in that string as I have done in my sample code but I just put it there to illustrate where I need my javascript variable to be. How can I achieve this??
The problem here is #url.content needs to be run on server, where JavaScript variable is not visible. Write an independent AJAX call to fetch content and than set content in data-url
You cannot use the Javascript variable directly into attribute.
A workaround can be to reorder the parameters of your url and setting the JavaScript variable in script tag.
<button id="myButton" data-url='#Url.Content("~/Catalogue_Items/ItemsActionViewPartial/")#Model.CatItemID?AsyncUpdateID=catalogue-view'></button>
I have reordered the url parameters here. The location parameter will be set by following script. Place this script just after the button element.
<script>
var button = document.getElementById('myButton');
var url=button.getAttribute('data-url');
url+="&LocationID=" + locid;
button.setAttribute('data-url',url);
</script>
You can put the value in the page using document.write, but you can't write it out inside the tag, you have to write out the entire tag. Example:
<script>
document.write('<div data-url="#Url.Content("~/Catalogue_Items/ItemsActionViewPartial/")#Model.CatItemID?LocationID=' + locid + '&AsyncUpdateID=catalogue-view">');
</script>

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

jQuery not pulling hidden field value on content page

I am running this script within a content page on my ASP.net site.
<script>
$(document).ready(function () {
var satShifts = $('#hidSat').val();
alert("Sat: " + satShifts);
});
</script>
On the page_Load event on the server I have this code:
hidSat.Value = "2";
The variable comes back as undefined in the alert window. I have this same process on the master page with another script and it works flawlessly. Is this an issue because it is a content page?
As far as i know,
if u use asp control in the content page,
the id is prefix with master name by .net compiler b4 render to html page.
So, here is my suggestion:
inspect the output html file with FireBug or Chrome
and see the name of ur hidden field.
if it is different, then u need to assign the id to some variable in JS.
like:
var tmp = '<%=hidSat.CliendID %>';
then,
$(tmp).val();
if it doesn't work, try with .html() method.
it will return all html code within ur hidden field.
Hope it works!
Change the code to below, since hidSat is server control.
var satShifts = $('#<%=hidSat.ClientID#').val();

Categories