manipulate jquery object from AJAX $.get - javascript

So I would like to know how to manipulate the Data I'm getting as a return from a $.get Method call to a link.
Example:
$.get('/index.php?id='+before+'&type=110', function(data){
var result = $(data).find('#ul1999 > *');
console.log(result);
},'text');
The response of the Webpage would be similar to this:
<div>
<ul id="ul1999">
<li>
something something
</li>
<li>
got a sub
<ul id="ul2014">
<li>
i'm the sub
</li>
</ul>
</li>
<li>
something 2
</li>
</ul>
</div>
And my returned value looks like this:
Object[li, li, li, li, li.last]
I now want to remove the parent element of id "ta200", so the entire li containing this id.
I tried to remove it with
var result = $(data).find('#ul1999 > *').not('#ta200').parent();
but it didn't work.
Maybe someone could tell me how to access the actual object and search for the id?

It should be as simple as this:
$(data).find("#ta200").parent().remove();
Here's a JSFiddle to better illustrate how you can manipulate an in-memory DOM like that and then retrieve the modified HTML: http://jsfiddle.net/troygizzi/xu6d3xhp/

Related

jQuery Editing innerHTML after selecting it with .html()

I am generating rows dynamically with PHP from DB, once it compiles the initial page code looks something like this:
Snippet
<div class="options" id="options">
<div class="left_wrap">
<ul>
<li class="col_id b-bottom"></li>
<li class="hazard_header"><h3>Hazard</h3></li>
<li class="hazard_input b-bottom"></li>
<li class="con_header b-bottom"><h3>Controls</h3></li>
<li class="cat_header"><h3>Consequence Category</h3></li>
<li class="cat_options"></li>
</ul>
</div>
<div class="right_wrap">
<h2>Inherent Risk (Assessed risk without controls)</h2>
<ul class="fields">
<li class="bg b-top b-right"><h3>Consequence Level</h3><br/><span class="con_level_val"></span></li>
<li class="b-top b-right"><h3>Probability</h3><br/>Possible</li>
<li class="bg b-top b-right"><h3>Exposure (frequency)</h3><br/></li>
After page load I grab contents of the wrap options.
jQuery Snippet:
content = $("div.options").html();
Which in turns stores the above code in the variable content. Now, my question is how can I edit contents of variable content. For example I need to add value to li with class Col_ID like 1,2,3,4 and same when I am deleting I need to modify the contents again.
How can I do something along the lines content.getElement?
If you really need to work with the HTML string, here's something you can do:
content = $("div.options").html();
var $content = $(content);
// now $content is a jQuery object with a bunch of (detached) elements
// you can use the common functions on it without problems, such as
$content.find("li.col_id").text("Some text");
// now you need to do something with $content, or everything you did will...
// ...be lost. You cold, for instance, update the other variable back:
content = $content.html();
// content now has the updated HTML
Now, if you don't need the HTML string at all, then you can work directly like:
content = $("div.options");
content.find("li.col_id").text("Some text");
// now the DOM was already updated as you are dealing with attached elements

Parsing structure/hierarchy of html and recreating it in a different form with javascript

I am trying to crawl some webpages with javascript to gather information about content's hierarchy. I'm using casperjs to do the crawling, that is working ok so far.
The information that I want to parse is structured like this:
<ul>
<a></a>
<li>
<h3>
<a>
Category
<span>Description for Category</span>
</a>
</h3>
<div>
<ul>
<li>
<a>SubCategory</a>
</li>
</ul>
</div>
</li>
</ul>
But what I want to end up with is this.
<ul>
<li>Category
<ul>
<li>SubCategory</li>
</ul>
</li>
</ul>
I want to use the above html in a different webpage, so basically I'll be writing it to a file from casperjs so that I can then copy paste it into another document. I'm crawling because it's a tedious thing to do manually (90 some pages and lots of data per page).
What's the best way to deconstruct/parse a hierarchy, and then recreate it? Stay within the DOM and restructure using JQuery? Pull it out into a tree structure and rebuild it later?
Please note that this is a particular solution and will only work for the specific layout of code that you provided:
I created a parser in jQuery that receives HTML markup in a textarea and converts it into the format that you are using:
$(function(){
$("button").click(function(){
//Read in HTML
$("#parser").html($("textarea").val());
//Parse
var categories = $("#parser > ul").find("li h3 a");
$(categories).find("span").remove();
//Output result
var output = "<ul>\n";
for(var i = 0; i < categories.length; i++)
{
//Get subcategories for this category
var subCategories = $($(categories[i])).closest("h3").siblings("div").find("ul li a");
//Add markup to output
output += "\t<li>" + minimize($($(categories[i])).html()) + "\n\t\t<ul>\n";
for(var j = 0; j < subCategories.length; j++)
{
output += "\t\t\t<li>"+$($(subCategories[j])).html() + "&lt/li>\n"
}
output += "\t\t</ul>\n\t</li>\n</ul>\n"
}
$("#result").html(output);
});
});
//Removes all white-space characters from the string.
function minimize(str)
{
return str.replace(/\s{2,}/g, '');
}
JSFiddle
It was a lot of work and is very customized. As I said earlier, if you look at the different selectors that are used here, this code is very tailored to this specific code layout.
Example:
var categories = $("#parser > ul").find("li h3 a");
This looks for a ul element just below parser that contains <a>s inside of <h3>s inside of <li>s to find the categories and then later uses
$($(categories[i])).closest("h3").siblings("div").find("ul li a");
which looks for an <h3> above the category <a> that has a sibling <div> with children <ul><li><a></a></li></ul>
So if the format is not this:
<ul>
<li>
<h3>
<a>Category</a>
</h3>
<div>
<ul>
<li>
<a>Subcategory</a>
</li>
</ul>
</div>
</li>
</ul>
It will not work.
I ended up going with this approach:
Scrape the tags from the existing website and assemble them into an array nested javascript object.
Writing them out with JSON.stringify to a file
Loading them into a new page as Javascript objects, and build the ul/li structure with a recursive function that traversed the javascript object.
I found it too hard to get my head around modifying the DOM as with the other answer(s). It was easier to break it down into multiple steps, with a well structured javascript object in the middle.

Using .click instead of onclick and getting a variable value

I have seen that the inline/html events like onclick, mouseover etc are being used less and less and it is advised to register events using Javascript.
I currently have some HTML like:
<ul id="supported-locations">
<li onclick="setLocationId(32);">Mexico</li>
<li onclick="setLocationId(35);">Mongolia</li>
</ul>
Which works fine but I want to now do this without the "onclick" in the HTML but still be able to retrieve the ID number.
The <li> elements are retrieved via AJAX while the user types into an input box it queries the database and retrieve the data without loading the page.
When the user clicks on one of the countries it will run the setLocationId function which just simply sets a hidden HTML form element with the ID of the selected country so I can use that once the form is submitted.
How do you register an event listener for these <li>'s when the countries and their ID's will always be different and changing depending on what the user types into the box?
Use a data attribute to hold the number. On the onclick event, read the attribute on the element that was clicked.
HTML:
<ul id="supported-locations">
<li data-code="32">Mexico</li>
<li data-code="35">Mongolia</li>
</ul>
JavaScript:
$("#supported-locations").on("click", "li", function() {
var li = $(this);
console.log(li.data("code"));
});
Example:
JSFiddle
<ul id="supported-locations">
<li data-id="32">Mexico</li>
<li data-id="35">Mongolia</li>
</ul>
in jQuery
$('#supported-locations').on('click','li',function(){
setLocationId($(this).data('id'));
})
<ul id="supported-locations">
<li data-id="32">Mexico</li>
<li data-id="35">Mongolia</li>
</ul>
jQuery(function(){
$('#supported-locations li').click(function(){
alert($(this).data('id'))
})
})
I recommend giving a class to the dynamically loaded elements, then use jquery .on(http://api.jquery.com/on/) method to register event listeneres to elements belonging to a class, even those that are dinamically loaded..
Then you could just read out the data stored in the element(in the form of data-something attributes).
<ul id="supported-locations>
<li id="32">Mexico</li>
<li id="35">Mongolia</li>
</ul>
//Jquery
$("#supported-locations > li").on('click',function(){
setLocationId($(this).attr('id'));
});
When you register your event, you still have the ability to use this, which is linked to the HTML element.
In other word, you still can do something like that
<li id="YOUR_ID">Mexico</li>
And get the id of the li tag
You can attach an event handler to the li:
<ul id="supported-locations">
<li id="location32">Mexico</li>
<li id="location35">Mongolia</li>
</ul>
$("#supported-locations li").click(function() {
alert($(this).attr("id"));
});
http://jsfiddle.net/puL95/
try this.
$("#supported-locations li").click(function() {
alert("me")
}

Inserting HTML into tag using JavaScript

I'm having a problem with JavaScript/jQuery at the moment where I'm trying to access the element inside the h4 element in my code. I'm doing this because I would like to dynamically display to the user how many guides are available in each "h4" section. For the PC section, it should display "4 reviews available" and for the Xbox One section, it should display "3 reviews available". However, both say " reviews available", and I'm assuming it's because I'm not using the jQuery functions properly. Here's the HTML code:
<h4><li class="console">PC (<span class="number"></span> reviews available)</li></h4>
<div class="gameList">
<ul>
<li class="game">Guide #1</li>
<li class="game">Guide #2</li>
<li class="game">Guide #3</li>
<li class="game">Guide #4</li>
</ul>
</div>
<h4><li class="console">Xbox One (<span class="number"></span> reviews available)</li></h4>
<div class="gameList">
<ul>
<li class="game">Guide #1</li>
<li class="game">Guide #2</li>
<li class="game">Guide #3</li>
</ul>
</div>
And here's the jQuery/JavaScript code:
$("h4").each(function() {
var node = $(this).children().children(); // gets node that has "number" class
var count = $(this).next().children().children().length; // gets number of li tags
node.innerHTML = count;
});
I tested whether or not it's properly getting the correct node and count by using the alert function for JavaScript, but for some reason, node.innerHTML = count won't display the contents of "content" properly in the element. Rather, it just displays a blank. Does anyone know why?
Its a jquery object not a DOM one..use this...
node.html(count);
node is a jQuery object here. It does not have "innerHTML". Instead you can use one of these:
node.html(count);
node.get(0).innerHTML = count;
node.get(0) will give you first DOM object from jQuery one.
A good practice is to prefix or suffix all jQuery objects with $ (e.g. $node), so that you will always know if a variable is meant to be a jQuery object.
use find() lot more cleaner and readable
$("h4").each(function() {
var $this=$(this);
var node = $this.find('.number');
var count = $this.next().find('li').length; // gets number of li tags
node.text(count); //or html()
});
and you have come invalid HTML li in h4 make sure you change that
working fiddle here
Do not use .children().children().
Only one .children() would do.
$(this).children('.game');
Also innerHTML is plain javascript. use .html(value) as node is JQuery Object.
$("h4").each(function() {
var node = $(this).children('.number');
var count = $(this).next().children('li').length;
node.html(count);
});
Reference to JQuery APIs:
.html()
.children()
$("h4").each(function() {
var $spanNumber = $('.console .number', this),
gameListCount = $(this).next().find('ul li').size();
$spanNumber.text(gameListCount)
});
You may use this also,
$("h4").each(function() {
var node = $(this).find('.number');
var count = $(this).next().find('.game').length;
node.html(count);
});

how to pick up string inside a <li> tag using jquery

I've a simple list and a form text-field:
<ul>
<li class="item">one</li>
<li class="item">two</li>
<li class="item">three</li>
<li class="item">four</li>
</ul>
<input id="field" type="text" />
When the user clicks on an <li> item, I want the string inside the li element to be assigned the value of the input field.
Something like:
$('.item').click( function(){
$('#field').val(/*put the string inside the li element just clicked*/);
});
So how do I get the string in the li element?
$('.item').click(function(){
$('#field').val($(this).html());
});
I'd personally suggest using a very similar suggestion to those already-posted, but with text() rather than html:
$('.item').click(
function(){
$('#field').val($(this).text());
});
It's a slim justification, but, as the docs note:
Unlike the .html() method, .text() can be used in both XML and HTML documents.
Otherwise they seem to be much the same.
Reference:
text();
.html() is what you're looking for. Please look it up in the API : http://api.jquery.com/html/
$('.item').click( function(){
$('#field').val($(this).html());
});
$('.item').click( function(){
$('#field').val($(this).html());
});

Categories

Resources