I have an XML file structured like this:
<movies>
<movie>
<title>A title</title>
<year>2016</year>
<boxoffice>18 million</boxoffice>
</movie>
<movie>
<title>Second title</title>
<year>2010</year>
<boxoffice>10 million</boxoffice>
</movie>
<movies>
I want to find all movies after year 2015 and show it in a table using jquery.
I get the xml using:
function getx() {
var x = $.ajax({
url: movies.xml,
datatype: "xml",
async: false
});
return x.responseXML;
}
and go though it using:
function find(year){
var x = getx();
$(x).find("year").each(function() {
if (Number($(this).text()) > Number(year) {
$(document.getElementById("results")).append("<tr><td>" + $(this).text() + "</td></tr>");
}
});
}
This returns creates a table row containing 2016. How could I modify this to search for one element and once found return all elements from the collection it belongs to? (I want to get a table row with title, year and boxoffice)
First: using an ajax call as sync is an issue, I suggest you to use a callback.
Second: in order to convert an xml to a jQuery object you can use jQuery.parseXML( data ). After the conversion you can use .filter() and .each() for selecting the elements you need and append them to the table.
In jquery the ID Selector (“#id”) is:
$('#results')
instead of:
$(document.getElementById("results"))
In order to get the siblings elements you can use: Node.nextSibling and Node.previousSibling or you can use the jQuery.prev() and jQuery.next().
The snippet:
var xml = '<movies>\
<movie>\
<title>A title</title>\
<year>2016</year>\
<boxoffice>18 million</boxoffice>\
</movie>\
<movie>\
<title>Second title</title>\
<year>2010</year>\
<boxoffice>10 million</boxoffice>\
</movie>\
</movies>';
var xmlDoc = $.parseXML( xml );
var jqXml = $(xmlDoc).find('year').filter((idx, ele) => {return +ele.textContent > 2015;});
jqXml.each(function(idx, ele) {
$('#results').append("<tr><td>" + ele.previousSibling.textContent +
"</td><td>" + ele.textContent + "</td><td>" +
ele.nextSibling.textContent + "</td></tr>");
})
td {
border: 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="results">
</table>
Related
Is there any definite way to retrieve the xPath of a angleSharp IElement
I'm trying to pass an IElement to a javaScript function, so I need a way to convert the angleSharp element to a javaScript Dom element
function selectLevels(element, name, level){
document.querySelectorAll("*").forEach(e => {
if(e.isEqualNode(element)){
e.setAttribute('level', level);
e.setAttribute('title', name);
}
})
}
I want to call this javaScript function which is in the page by passing an element from the C# code bellow, but I get an angleSharp not found error from the page.
IElement element = mainDoc.QuerySelector("strong");
Page.ClientScript.RegisterStartupScript(this.GetType(), "SelectLevel", "selectLevels('" + element + "', '" + name + "', '" + level + "')", true);
If you have a HTML document with JavaScript code and want to call a (global) function in the JavaScript code from C# then the following example works for me with AngleSharp 0.15 and AngleSharp.Js 0.14:
static async Task Main()
{
var html = #"<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script>
function selectLevels(element, name, level){
element.dataset.level = level;
element.dataset.title = name;
}
</script>
</head>
<body>
<h1>Test</h1>
<section data-level=1 data-title='section 1'>
<h2>Section test</h2>
</section>
</body>
</html>";
var jsService = new JsScriptingService();
var config = Configuration.Default.With(jsService);
var context = BrowsingContext.New(config);
var document = await context.OpenAsync(req => req.Content(html));
var selectLevels = jsService.GetOrCreateJint(document).GetValue("selectLevels");
var jsElement = JsValue.FromObject(jsService.GetOrCreateJint(document), document.QuerySelector("section"));
selectLevels.Invoke(jsElement, "2", "section 2");
Console.WriteLine(document.DocumentElement.OuterHtml);
}
So basically you get the function with e.g. jsService.GetOrCreateJint(document).GetValue("selectLevels"); and call it with its Invoke method, passing in string arguments for the simple types and the IElement converted with JsValue.FromObject e.g. JsValue.FromObject(jsService.GetOrCreateJint(document), document.QuerySelector("section")).
I'm working on displaying an RSS feed in a website through the use of jQuery and AJAX. One of the strings from the source XML file are wrapped in a <category> tag, and there are multiple of these returned. I'm getting the source data like follows:
var _category = $(this).find('category').text();
Because there are multiple categories returned with this method, say the following:
<category>Travel</category>
<category>Business</category>
<category>Lifestyle</category>
I'm getting strings returned like so:
TravelBusinessLifestyle
My end goal is to see each of these separate strings returned and wrapped in individual HTML elements, such as <div class="new"></div>.
I did end up trying the following:
var _categoryContainer = $(this)
.find('category')
.each(function () {
$(this).wrap( "<div class='new'></div>" );
});
among quite a few other variations.
This is all being appended to a HTML structure similar to the following.
// Add XML content to the HTML structure
$(".rss .rss-loader")
.append(
'<div class="col">'
+ <h5 class="myClass">myTitle</h5>
+ _category
+ "</div>"
);
Any suggestions would be much appreciated!
if it's a simple html which is mentioned in a question. you can use something like below.
var html="<category>Travel</category><category>Business</category><category>Lifestyle</category>"
var htmlObj=$.parseHTML(html);
var container=$("#container")
$.each(htmlObj,function(i,o){
container.append("<div class='new'>"+o.innerText+"</div>")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='container'></div>
Same as first answer, but without jquery
let container = document.querySelector('div#container');
document.querySelectorAll('category').forEach(element => {
let div = document.createElement('div');
div.innerText = element.innerText;
container.appendChild(div);
})
<category>Travel</category><category>Business</category><category>Lifestyle</category>
<div id="container"></div>
I want to store some information in DOM elements (rows of table). I think I can do it using jQuery's data() function. I wrote some test code and found out that I can't get the stored data from elements using jQuery selectors. Is it possible? Maybe I'm doing something wrong?
Here is the simple code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQuery data() test</title>
<script src="https://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
</head>
<body>
<table id="myTable">
<tbody>
<tr id="rowPrototype" style="display:none;">
<td class="td1"></td>
<td class="td2"></td>
</tr>
</tbody>
</table>
<script>
var table = $("#myTable");
for (var i = 0; i < 5; i++) {
var newRow = $("#rowPrototype").clone();
newRow.removeAttr("style");
newRow.removeAttr("id");
$.data(newRow, "number", i);
console.log("Data added to row: " + $.data(newRow, "number"));
var tds = newRow.find("td");
tds.text("test");
table.append(newRow);
}
var trs = table.find("tr");
trs.each(function () {
var tr = $(this).text();
var data = $.data(tr, "number");
console.log("number: " + data);
});
</script>
</body>
</html>
I expect the following output:
number: undefined (row prototype)
number: 0
number: 1
number: 2
number: 3
number: 4
But actual is:
number: undefined
number: undefined
number: undefined
number: undefined
number: undefined
number: undefined
So what's wrong with this code?
UPD
You can test it here: https://jsfiddle.net/rfrz332o/3/
$.data() expects an actual DOM element as the first argument, not a jQuery object. You can $(selector).data() with jQuery objects. I'd suggest you change this:
$.data(newRow, "number", i);
console.log("Data added to row: " + $.data(newRow, "number"));
to this:
newRow.data("number", i);
console.log("Data added to row: " + newRow.data("number"));
And, then change this:
var trs = table.find("tr");
trs.each(function () {
var tr = $(this).text();
var data = $.data(tr, "number");
console.log("number: " + data);
});
to this:
table.find("tr").each(function () {
console.log("number: " + $(this).data("number"));
});
You messed with data method. You weren't applying data to dynamic created row. To see result, please check your console.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQuery data() test</title>
<script src="https://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
</head>
<body>
<table id="myTable">
<tbody>
<tr id="rowPrototype" style="display:none;">
<td class="td1"></td>
<td class="td2"></td>
</tr>
</tbody>
</table>
<script>
var table = $("#myTable");
for (var i = 0; i < 5; i++) {
var newRow = $("#rowPrototype").clone();
newRow.removeAttr("style");
newRow.removeAttr("id");
newRow.data("number", i);
console.log("Data added to row: " + newRow.data("number"));
var tds = newRow.find("td");
tds.text("test");
table.append(newRow);
}
var trs = table.find("tr");
trs.each(function () {
var tr = $(this).text();
var data = $(this).data("number")
console.log("number: " + data);
});
</script>
</body>
</html>
$.data() expects DOM element, not jQuery object. Add [i] or use .get(i) at $.data(newRow[i], "number", i); and all js that follows where $.data() is used to reference DOM element.
There is also an issue with the for loop. If there is actually only one tr element and two td elements within #myTable, when i reaches 2 , if the selector included i the result would be undefined, as the maximum index of td elements would still be 1 within the cloned table ; whether $.data() or .data() is used. Similarly for the one tr element within #myTable; when i reaches 1
jQuery.data( element, key, value )
element
Type: Element
The DOM element to associate with the data.
I'm a beginner in javascript and I have a little problem with my code. I found an exercise and i'm trying to do it. I have to write a function that will insert text from variable into table. I never met something like this. This variable looks like four objects in array. I want to show text in the table when I press a button. There are two buttons. When I press "Fizyka" button i should see:
Fizyka
Ola Kowal
Ela Nowak
and when I press "Chemia":
Chemia
Ala Goral
Ula Szpak
So this is my code. All i can edit is function show(study):
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
</head>
<body>
<button onclick="show('fizyka')">Fizyka</button>
<button onclick="show('chemia')">Chemia</button>
<div id="list"></div>
<script>
var student=[
{name:"Ola", second_name:"Kowal", study:"fizyka"},
{name:"Ela", second_name:"Nowak", study:"fizyka"},
{name:"Ala", second_name:"Goral", study:"chemia"},
{name:"Ula", second_name:"Szpak", study:"chemia"},
];
function show(study)
{
if (study==='fizyka')
{
document.getElementById("list").innerHTML = "<h2>student.kierunek</h2><ul><li>student.name + " " + student.second_name</li><li>student.name + " " + student.second_name</li></ul>";
}
if (study==='chemia')
{
document.getElementById("list").innerHTML = "<h2>student.kierunek</h2><ul><li>student.name + " " + student.second_name</li><li>student.name + " " + student.second_name</li></ul>";
}
}
</script>
</body>
</html>
It's not working. I don't know how to insert text from this variable into table.
There is several problem with your code. I have written piece of code which is working and you can use it and inspire.
<button onclick="show('fizyka')">Fizyka</button>
<button onclick="show('chemia')">Chemia</button>
<div id="list"><h2></h2><ul></ul></div>
<script>
//Student array
var student=[
{name:"Ola", second_name:"Kowal", study:"fizyka"},
{name:"Ela", second_name:"Nowak", study:"fizyka"},
{name:"Ala", second_name:"Goral", study:"chemia"},
{name:"Ula", second_name:"Szpak", study:"chemia"},
];
function show(study)
{
console.log('ENTER show('+study+')');
//Select h2 element
var header = document.getElementById("list").firstChild;
//Set h2 element text
header.innerHTML = study;
//Select ul element
var list = document.getElementById("list").lastChild;
//Set inner html to empty string to clear the content
list.innerHTML = "";
//loop through students and set the appropriate html element values
for(var i = 0; i < student.length; i++){
//check whether student[i] studies study which is put as a paramter into the function
if(student[i].study === study){
//Create new li element
var li = document.createElement('li');
//Into li element add a new text node which contains all data about the student
li.appendChild(document.createTextNode(student[i].name + ' ' + student[i].second_name));
//add li element into ul
list.appendChild(li);
}
}
console.log('LEAVE show('+study+')');
}
</script>
i want to print an array with js and just add to every element some data with html()
the code i use is :
<script type="text/javascript">
$(document).ready(function() {
var testArray = ["test1","test2","test3","test4"];
for(var i=0;i<testArray.length;i++){
document.write(" " +testArray[i]+"<br />").html("is the best");
}
});
</script>
but it doesnt works.
HTML:
<div id="myDIV"></div>
JS:
$(document).ready(function() {
var testArray = ["test1","test2","test3","test4"];
var vPool="";
jQuery.each(testArray, function(i, val) {
vPool += val + "<br /> is the best <br />";
});
//We add vPool HTML content to #myDIV
$('#myDIV').html(vPool);
});
Update:
Added demo link: http://jsfiddle.net/aGX4r/43/
Syntax problem mate!
Let me get that for you!
// first create your array
var testArray = ["test1", "test2", "test3", "test4"];
// faster ready function
$(function(){
for( var i=0; i<testArray.length; i++ ) {
current = testArray[i] + '<br />' + 'is the best'; // this is a string with html in it.
$(current).appendTo("body"); // add the html string to the body element.
}
});
First. document.write it's not a good practice.
Then, you code have a little error: Function (as in document.write) doesn't have html method. Thats a jQuery method.
So, in order to print the array in the body, you could do:
$('p').html(["test1","test2","test3","test4"].join('<br />')).appendTo(document.body);
It's a little difficult to tell what you want to do, but if you want to append to an element in your DOM, use jQuery.append();
for(var i=0;i<testArray.length;i++) {
jQuery('#mydiv').append(testArray[i]);
}