How do i use jquery on items from $.get(url) - javascript

I would like to .get a page and then use jquery to find elements such as links. How do i make $('#blah') search the get data instead of the page?

You should be able to create a dom element from the returned HTML without actually adding it to the document, and then search through that using the jQuery methods:
jQuery.get('/my_url/', function(html_data) {
// If your html_data isn't already wrapped with an HTML object, you may
// need to wrap it like so:
//
// var jQueryObject = $("<div>" + html_data + "</div>");
var jQueryObject = $(html_data);
jQueryObject.find("a.link_class");
// Or, as stated by gregmac below, you could just do the following:
$("a.link_class", html_data);
// or, if wrapping is required:
$("a.link_class", "<div>" + html_data + "<div>");
});

For finding links or a specific element like your example, you can do this:
$.get('test.html', function(data) {
var links = $('a', data); //Use the response as the context to search in
var blah = $('#blah', data);
});

I'm pretty sure you'll be limited to only getting links from a local server/page too.
// create blank array
var links = new Array();
// where should we $.get
var url = '/menus';
$.get(url, function(data) {
// get anchors from the url
links = $(data).find('a');
// loop through all of them
for(i=0; i<links.length; i++)
{
// do something (may alert a lot of links... be prepared)
alert($(links[i]).attr('href'));
}
});

you can simply do this:
$('#result').load('ajax/test.html #container');
only the content of #container will be shown.

Related

Manipulate var in jquery by doing find and text

I use a WYSIWYG editor in my page. I collect the HTML in a callback function. I would like now change the content with jQuery. For that I do a find() to select the text I want to replace. Then I want to replace it, but I'm stuck!
$('.save').click(function() {
var html = $('#edit').editor('get_html');
console.log(html)
var ma_societe_OLD = $(html).find('.ma_societe').attr('data');
var ma_societe = $(html).find('.ma_societe').text();
if (ma_societe === ma_societe_OLD) {
$(html).find('.ma_societe').text('dfdsfsdfds');
}
console.log(html);
});
As you can see, I want to replace the content of the span with my own text. But it's not working.
The issue is because you're making amendments to the jQuery object, but you never store those changes anywhere. You either create a new jQuery object containing the original, unchanged html, or return the html string directly.
Instead, create $(html) in a variable, make your changes to it, then work with it as needed. Something like this:
$('.save').click(function() {
var html = $('#edit').editor('get_html');
var $html = $(html);
var $maSociete = $html.find('.ma_societe')
if ($maSociete.text() === $maSociete.attr('data')) {
$maSociete.text('dfdsfsdfds');
}
var result = $html[0].outerHTML
console.log(result);
});

Chrome is outputting something different than other browsers/IDE

Problem
I am making a wikipedia viewer for FreeCodeCamp. When I execute my code using Jetbrains Webstorm IDE, I get a total of 10 extra divs created at the end of my search results.
When I do so using JSfiddle, I see the correct results, which should just be the initial 10 search results, and not +10 more empty div containers.
Any idea what's going on?
Troubleshooting
After some more digging into it, it seems like this is more of a browser issue than an IDE issue. It looks like it's just Chrome that's doing this? I tried on Firefox and IE, and it runs as normal, just like the JSfiddle. I have also tried clearing all cookies and cache on Chrome.
When I open the console log and look at the elements, in Chrome, there are clearly 10 extra empty divs, as shown here.
But in Firefox, the same code does NOT create the divs, as shown here.
Edit: Okay, so in Chrome, if you hit enter, instead of clicking on the search button, it creates the extra divs. But if you click on the search icon, the results appear correctly. Can anyone explain why? Did I place/write the .keyup() code block incorrectly?
Here's a picture of said issue.
Javascript portion:
$(function(){
$("#search-bar").keyup(function(event) {
if(event.keyCode === 13) {
$(".btn").click();
}
});
$(".btn").click(function() {
$("#results").empty();
var searchTerm = $("#search-bar").val();
var url = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + searchTerm + "&utf8=&format=json&origin=*";
console.log(url);
$.ajax({
cache: false,
url: url,
type: 'GET',
success: function(data) {
// Create a blank array to store the specific URLs in
var urlArr = [];
for (var i=0; i <= data.query.search.length; i++) {
// Adding the variables for use here
var headerData = data.query.search[i].title;
var urlSearchTerm = headerData.replace(/\s/gi, '_');
var snippetData = data.query.search[i].snippet + "...";
var createDiv = document.createElement("div");
var createHeader = document.createElement("h1");
var createSnippet = document.createElement("p");
var divId = "div" + i.toString();
var headerId = "header" + i.toString();
var snippetId = "snippet" + i.toString();
var resultUrl = "https://en.wikipedia.org/wiki/";
urlArr[i] = resultUrl + urlSearchTerm;
// Create the div element, give it an id
// Create <h1> element, give it an id
// Create <p> element, give it an id
// Give each <div> a class
createDiv.setAttribute("id", divId);
createHeader.setAttribute("id", headerId);
createSnippet.setAttribute("id", snippetId);
createDiv.setAttribute("class", "each-result");
// appending <div> elements in the #results id element in body
// appending <h1> element to the div element
// appending <p> element to the div element
document.getElementById("results").appendChild(createDiv);
document.getElementById(divId).appendChild(createHeader);
document.getElementById(divId).appendChild(createSnippet);
// populate json data into <h1> element
// populate json data into <p> element
$("#header" + i.toString()).text(headerData);
$("#snippet" + i.toString()).html(snippetData);
// create a click event handler that does 2 things
// 1. Gives each div an element that has a URL in the resultUrl array
// 2. Opens that url in a new window
(function(i) {
$("#div" + i.toString()).click(function() {
window.open(urlArr[i]);
});
}(i));
}
}
});
});
$("#random-wiki-button").click(function() {
window.open("https://en.wikipedia.org/wiki/Special:Random");
});
});
Actual full code including html/css + JS: JSfiddle
Maybe try updating chrome?
I would try to change your for loop to for (var i=0; i < 10; i++) { that way the increment stops at the 10th item.
edited.

js How to add href + text onclick

I need to pass (using javascript) text inside span to href
<div class='tableCell'><span>information</span></div>
<div class='tableCell'><span>contact</span></div>
<div class='tableCell'><span>about</span></div>
for example when i click to about link must be example.com/tag/about/
Here is my Answer. I'm using Javascript to manipulate the DOM to add a new element with the href equal to the inner text within the span element.
I hope you find this answer helpful.
Thanks.
var spans = document.getElementsByTagName('span')
var baseUrl = 'http://example.com/tag/'
for(var i=0; i<spans.length; i++)
{
var curElement = spans[i];
var parent = curElement.parentElement;
var newAElement = document.createElement('a');
var path = baseUrl+curElement.innerHTML;
newAElement.setAttribute('href', path);
newAElement.appendChild(curElement);
parent.appendChild(newAElement)
}
DEMO
The simplest way:
$( "span" ).click(function() {
var link = 'http://yousite.com/tag/'+ $(this).text().replace(/ /, "-")+"/";
window.location.href= link.toLowerCase();
});
DEMO
http://codepen.io/tuga/pen/yNyYPM
$(".tableCell span").click(function() {
var link = $(this).text(), // will provide "about"
href = "http://example.com/tag/"+link; // append to source url
window.location.href=href; // navigate to the page
});
You can try the above code
You do not have links but span in your html. However, you can get build the href you want and assign it to an existing link:
$('div.tableCell').click(function(){
var href = 'example.com/tag/' + $(this).find('span').text();
})
Lets work with pure javascript, I know you want to use jQuery but I am really sure too many people can't do this without looking in to web with pure javascript. So here is a good way.
You can follow it from jsFiddle
var objectList = document.getElementsByClassName("tableCell");
for(var x = 0; x < objectList.length; x++){
objectList[x].addEventListener('click', function(){
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML;
});
}
Lets work on the code,
var objectList = document.getElementsByClassName("tableCell");
now we have all element with the class tableCell. This is better than $(".tableCell") in too many cases.
Now objectList[x].addEventListener('click', function(){}); using this method we added events to each object.
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML; with this line if somebody clicks to our element with class: We will change the link to his first child node's text.
I hope it is useful, try to work with pure js if you want to improve your self.
Your Method
If you always are going to have the url start with something you can do something like this. The way it is set up is...
prefix + THE SPANS TEXT + suffix
spaces in THE SPANS TEXT will be converted to -
var prefix = 'http://example.com/tag/',
suffix = '/';
$('span').click(function () {
window.location.href = prefix + $(this).text().replace(' ', '-').trim().toLowerCase() + suffix;
//An example is: "http://example.com/tag/about-us/"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tableCell'><span>Information</span></div>
<div class='tableCell'><span>Contact</span></div>
<div class='tableCell'><span>About</span></div>
You can adjust this easily so if you want it to end in .html instead of /, you can change the suffix. This method will also allow you to make the spans have capitalized words and spaces.
JSBIN

jQuery add id to an element that is being appended to the body

I have the following function:
simpleModal: function (data, id) {
var responseHtml = data;
// Append the modal HTML to the DOM
var modalInstance = $('body').append(modalHtml);
$(modalInstance).attr('id', id);
$(id).find('.uiModalContent').width(480);
$(id).find('.uiModalContent').height(320);
// Hide the modal straight away, center it, and then fade it in
$(id).find('.uiModal').hide().center().fadeIn();
// Dynamically load in the passed data from the call
$(id).find('.uiModalContent').html($(responseHtml));
$(id).find('.uiModalContent').removeClass('loading');
$(id).find('.ModalClose').live('click', function (e) {
e.preventDefault();
$(this).parents('.uiModal').fadeOut(function () { $(this).parents('.uiModalWrapper').remove() });
});
},
when called like:
uiModal.simpleModal('<p>An error has occured</p>','TestError');
it should append the modal to the body with the passed content and give the modalHtml an id that is also passed. However it gets confused to appends the id to the body instead of the html. How do I get around this? Thanks
This is because the append method returns the element you are appending to, rather than the element you're appending.
Instead, you can use the appendTo method, and use it as follows;
var modalInstance = $(modalHtml).appendTo('body');
You also need to be using $('#' + id) as the ID selector as opposed to $(id); otherwise you'll end up looking for all elements with the tag name of TestError.
Additionally, you should seriously consider caching the result of $('#' + id); you're performing the same DOM lookup operation 6 times; which is totally unnecessary, as you have exactly the same jQuery object cached in var modalInstance; replace all instances of $('#' + id) to modalInstance
This point applies to $(id).find('.uiModalContent') as well; cache it!
var uiModelContent = modelInstance.find('.uiModalContent');
uiModelContent.height(320);
uiModelContent.width(480);
uiModelContent.html($(responseHtml));
uiModelContent.removeClass('loading');
Although you can also chain your methods for the same result;
modelInstance.find('.uiModalContent').height(320).width(480).html($(responseHtml)).removeClass('loading');

Filtering the list of friends extracted by Facebook graph api ( more of a JavaScript/Jquery question than Facebook API question)

Hello there JavaScript and Jquery gurus, I am getting and then displaying list of a facebook user's friend list by using the following code:
<script>
function getFriends(){
var theword = '/me/friends';
FB.api(theword, function(response) {
var divInfo = document.getElementById("divInfo");
var friends = response.data;
divInfo.innerHTML += '<h1 id="header">Friends/h1><ul id="list">';
for (var i = 0; i < friends.length; i++) {
divInfo.innerHTML += '<li>'+friends[i].name +'</li>';
}
divInfo.innerHTML += '</ul></div>';
});
}
</script>
graph friends
<div id = divInfo></div>
Now, in my Facebook integrated website, I would eventually like my users to choose their friends and send them gifts/facebook-punch them..or whatever. Therefore, I am trying to implement a simple Jquery filter using this piece of code that manipulates with the DOM
<script>
(function ($) {
// custom css expression for a case-insensitive contains()
jQuery.expr[':'].Contains = function(a,i,m){
return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
function listFilter(header, list) { // header is any element, list is an unordered list
// create and add the filter form to the header
var form = $("<form>").attr({"class":"filterform","action":"#"}),
input = $("<input>").attr({"class":"filterinput","type":"text"});
$(form).append(input).appendTo(header);
$(input)
.change( function () {
var filter = $(this).val();
if(filter) {
// this finds all links in a list that contain the input,
// and hide the ones not containing the input while showing the ones that do
$(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("a:Contains(" + filter + ")").parent().slideDown();
} else {
$(list).find("li").slideDown();
}
return false;
})
.keyup( function () {
// fire the above change event after every letter
$(this).change();
});
}
//ondomready
$(function () {
listFilter($("#header"), $("#list"));
});
}(jQuery));
</script>
Now, This piece of code works on normal unordered list, but when the list is rendered by JavaScript, it does not. I have a hunch that it has to do something with the innerHTML method. Also, I have tried putting the JQuery filter code within and also right before tag. Neither seemed to work.
If anyone knows how to resolve this issue, please help me out. Also, is there a better way to display the friends list from which users can choose from?
The problem is here:
$(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("a:Contains(" + filter + ")").parent().slideDown();
Since you're rendering this:
divInfo.innerHTML += '<li>'+friends[i].name +'</li>';
There is no anchor wrapper, the text is directly in the <li> so change the first two lines to look in those elements accordingly, like this:
$(list).find("li:not(:Contains(" + filter + "))").slideUp();
$(list).find("li:Contains(" + filter + ")").slideDown();
You could also make that whole section a bit faster by running your Contains() code only once, making a big pact for long lists, like this:
$(input).bind("change keyup", function () {
var filter = $(this).val();
if(filter) {
var matches = $(list).find("li:Contains(" + filter + ")").slideDown();
$(list).find("li").not(matches).slideUp();
} else {
$(list).find("li").slideDown();
}
});
And to resolve those potential (likely really) innerHTML issues, build your structure by using the DOM, like this:
function getFriends(){
var theword = '/me/friends';
FB.api(theword, function(response) {
var divInfo = $("#divInfo"), friends = response.data;
divInfo.append('<h1 id="header">Friends/h1>');
var list = $('<ul id="list" />');
for (var i = 0; i < friends.length; i++) {
$('<li />', { text: friends[i].name }).appendTo(list);
}
divInfo.append(list);
});
}
By doing it this way you're building your content all at once, the <ul> being a document fragment, then one insertion....this is also better for performance for 2 reasons. 1) You're currently adding invalid HTML with the .innerHTML calls...you should never have an unclosed element at any point, and 2) you're doing 2 DOM manipulations (1 for the header, 1 for the list) after the much faster document fragment creation, not repeated .innerHTML changes.

Categories

Resources