I am trying to refer to object in second column (object link_icon) and based on .json data, I am assigning new url.
Structure of my html:
<div class="details">
<h1 id="title">title</h1>
<h3 id="author">
author
</h3>
</div>
<a href="https://www.google.pl/">
<div><i class="link_icon"></i></div>
</a>
$(function(){
var url = 'img_and_data/' + randomNumbers[bgImgIndex] +'.json';
var title = $("#title");// the id of the heading
var author = $("#author a");// id of author
var link_icon = $(".link_icon a"); // <------- problem probably is here
$.getJSON(url, function (data) {
title.text(toTitleCase(data.title));
author.text(data.copyright);
author.attr("href", data.url);
link_icon.attr("href", data.permalink);
});
}
Here is my full code:
https://jsfiddle.net/cvv0sen8/8/
How should I refer to link_icon to modify href?
Could you help me?
JSON:
{
"title": "example title",
"copyright": "example author",
"permalink": "https://www.bing.com/",
"url": "http://www.yahoo.com"
}
var link_icon = $(".link_icon a");
Your selector here means "every a tag which has a tag with class link_icon as a parent". Problem is your html document doesn't contain any a tag in link_icon: your selector will return nothing.
You may change your html like this:
<div><a class="link_a" href="#"><i class="link_icon"></i></a></div>
And your js:
var link_a = $(".link_a");
// ...
link_a.attr("href", data.permalink);
Related
I wish to extract all links and text from the HTML source code and add it to a multidimensional array using the google come console
Code snippet -- repeated 10 times
<div class="Contentx">
<a style='text-decoration:none;' href='Tate-Tea.com'>
<h2>Tate Tea<br>
<span class='Fis'>Tate-Tea.com</a></span>
</h2>
</span>
The result would be an array
{'Tate-Tea.com','Tate Tea'}
I am having a difficulty finding a style='text-decoration
So I guess match
Loop around and append to the array ..
Var list = []
document.querySelectorAll('a[style.textDecoration:none]')
.each(function(){
var URL = $(this).attr("href");
var URL_name = alert($(this).text());
..# append to list
list.push ({ URL : '',
URL_name : ''
}}
});
document.querySelector('a[style]').href
document.querySelector('a[style]').text
I can get one of them by using following
First find all a tag and then manipulate those of that meats this style.textDecoration == "none" condition.
Try this one:
var list = []
document.querySelectorAll('a')
.forEach(function (tag) {
if (tag.style.textDecoration == "none") {
var URL = tag.getAttribute("href");
var URL_name = alert(tag.text);
list.push({
URL: URL,
URL_name: URL_name
})
}
});
console.log(list);
<div class="Contentx">
<a style='text-decoration:none;' href='Tate-Tea.com'> <h2>Tate Tea<br><span class='Fis'>Tate-Tea.com</a></span></h2> </span>
</div>
I'd appreciate some help with iteratively generating the beneath div based on the amount of items in a Javascript dictionary.
<div class="container" style="padding-bottom: 10px;">
<div class="dropdown" style="padding: 10px;">
<a href="#">TOP 3 PS5 HEADSETS<i class="fa fa-chevron-down"></i>
</a>
<ul>
<div id="links">
<center>
<p>3: ↓ INSERT TITLE FOR STEELSERIES ↓</p>
</center>
<div class="product">
<img src="img/products/h-steelseries.png">
<a class="link" href="INSERT LINK HERE">Read More</a>
</div>
<center>
<p>3: ↓ INSERT TITLE FOR OTHER↓</p>
</center>
<div class="product">
<img src="img/products/h-other.png">
<a class="link" href="INSERT LINK HERE">Read More</a>
</div>
</div>
</ul>
</div>
</div>
Beneath is the read.js file that contains the items in which I wish to generate the div class "product" for.
I'd really apprecaite any help with this.
var prod_obj = {
"headphone_products" : {
"title": "Steelseries",
"IMAGE": "h-steelseries.png",
"HREF" : "steelseries.html"
},
"other_products" : {
"title": "Other product",
"IMAGE": "h-other.png",
"HREF" : "other.html"
}
};
I have looked at other answers and couldn't find an example of a dictionary of object that was used to automatically generate divs. I intend on using this to list items on a website and would like to append objects to the dictionary and them to automatically generate a new div for each object once the script is executed.
Thank you for your time.
You can simply loop over the object and create the desired nodes inside the loop.
Here's a simpler version of the same.
var prod_obj = {
"headphone_products": {
"title": "Steelseries",
},
"other_products": {
"title": "Other product",
}
};
for (let keys in prod_obj) {
const div = document.createElement("div");
div.innerText = prod_obj[keys].title
document.body.appendChild(div)
}
You can use for-in loops and template literals to achieve what you want to achieve here.
const prod_obj = {
"headphone_products": {
"title": "Steelseries",
"image": "h-steelseries.png",
"href": "steelseries.html"
},
"other_products": {
"title": "Other product",
"image": "h-other.png",
"href": "other.html"
}
};
const div = document.getElementById('insertHere');
for (let products_key in prod_obj) {
let {title, image, href} = prod_obj[products_key];
let html = `<p>Title: ${title}, Image: ${image}, href: ${href}</p>`;
div.insertAdjacentHTML('beforeend', html);
}
<div id="insertHere">
</div>
What you describe sounds like a suitable candidate for a template which, according to the documentation on MDN says:
The HTML Content Template () element is a mechanism for
holding HTML that is not to be rendered immediately when a page is
loaded but may be instantiated subsequently during runtime using
JavaScript.
The following uses a simple class to load a new instance of the designated template for each product found within the source data ( what you refer to as a dictionary ). Once the template has been loaded from the shadows you can manipulate the contents as you wish. If you change the design of the template you change the design of the final layout. In the original HTML there is no span element surrounding the individual products but the way I wrote the template loader( for a specific job ) clones the first child element entirely - so a span will not affect layout unless styled specifically to do so.
class TemplateLoader{
constructor( id ){
this.id=id;
return this.create();
};
gettemplate(){
return document.querySelector( 'template[ data-id="'+this.id+'" ]' ) || false
};
clone(){
let tmpl=this.gettemplate();
return tmpl ? tmpl.content.firstElementChild.cloneNode( true ) : false;
};
gettarget(){
return document.querySelector( 'div[ id="'+this.id+'" ]' ) || false;
};
create(){
let tmpl=this.clone();
if( tmpl ){
let target=this.gettarget();
target.appendChild( tmpl );
return tmpl;
}
return false;
};
};
var prod_obj = {
'headphone_products' : {
'title': 'steelseries',
'image': 'h-steelseries.png',
'href' : 'steelseries.html'
},
'other_products' : {
'title': 'other product',
'image': 'h-other.png',
'href' : 'other.html'
},
'banana':{
'title':'curvy & yellow',
'image':'b-a-nana.png',
'href':'banana.html'
}
};
let id='links';
Object.keys( prod_obj ).forEach( cat => {
let data=prod_obj[ cat ];
let oTmpl=new TemplateLoader( id );
oTmpl.querySelector('center > p').textContent=data.title;
oTmpl.querySelector('div.product > img').src=['img/products',data.image].join('/');
oTmpl.querySelector('div.product > a.link').href=data.href;
});
<!-- regular HTML -->
<div class='container'>
<div class='dropdown'>
<a href='#'>TOP 3 PS5 HEADSETS<i class='fa fa-chevron-down'></i></a>
<ul>
<div id='links'>
<!-- items will be populated here -->
</div>
</ul>
</div>
</div>
<!-- our template that will be used to generate new content within the above, regular HTML' -->
<template data-id='links'>
<span>
<center>
<p></p>
</center>
<div class='product'>
<img />
<a class='link'>Read More</a>
</div>
</span>
</template>
The traditional way to add content to the DOM on-the-fly is to use a series of calls to createElmenent and appendChild (which is less error-prone than just inserting HTML strings). And you can loop through your data object's keys and extract the details you need to configure your new DOM elements. This script does both of these things in a function called updateDOM, which invokes the appendProductDetails function once per product.
I changed the hrefs to create functional (if arbitrary) links, and of course the images don't show up because they don't exist on StackOverflow's server. See the in-code comments for further explanation.
const currentProds = getProductsToShow();
updateDOM(currentProds);
function updateDOM(prod_obj) {
// Identifies parent div
const linksDiv = document.getElementById("links");
// Clears parent div
linksDiv.innerHTML = "";
// Loops through productName (keys) in prod_obj
const productNames = Object.keys(prod_obj);
for (let productName of productNames) {
// Gets details (inner object) for each product
const details_obj = prod_obj[productName];
// Creates, configures, and appends new elements for each product
appendProductDetails(linksDiv, details_obj);
}
}
function appendProductDetails(parentElement, detailsObject) {
const
// Gets local copies of values via "destructuring"
{ title, image, href } = detailsObject,
path = "img/products/", // Defines path to images
// Creates elements to add to the DOM
productDiv = document.createElement("div"),
titleP = document.createElement("p"),
img = document.createElement("img"),
anchor = document.createElement("a");
// Configures newly created elements
productDiv.classList.add("product");
titleP.textContent = title;
img.src = path + image;
img.alt = image;
anchor.classList.add("link");
anchor.href = href;
anchor.textContent = "Read More";
// Puts children into productDiv
productDiv.appendChild(titleP);
productDiv.appendChild(img);
productDiv.appendChild(anchor);
// Attaches everything to the DOM
parentElement.appendChild(productDiv);
}
// Provides demo data
function getProductsToShow() {
const productsObj = {
"headphone_products": {
"title": "Steelseries",
"image": "h-steelseries.png", // In img/products/
"href": "https://stackoverflow.com"
},
"other_products": {
"title": "Other product",
"image": "h-other.png",
"href": "https://eloquentjavascript.net/"
}
};
return productsObj;
}
.container{ width: 250px; text-align: center; }
.dropdown > a{ text-decoration: none; }
p{ margin: -0.1rem 0; font-size: 1.2rem; }
.product{ padding: 0.5rem ; }
.link{ margin-left: 1rem; }
<div class="container">
<div class="dropdown">
PS5 HEADSETS
<div id="links"></div>
</div>
</div>
(A more modern approach would be to repeatedly clone the contents of a template element and to use slot elements to insert corresponding product details into each new instance.)
What I'm trying to do is add for each items in a xml file their content to a html page. I'm trying to make it so that every item content is inside an <article> tag. However, It's my first time using jQuery and my end result is not what I want.
let $items = $(xmlContent).find("item");
$items.each(function() {
let title = $(this).find('title').text();
let date = $(this).find('pubDate').text();
let link = $(this).find('link').text();
let guid = $(this).find('guid').text();
let photo = $(this).find('media').html();
$("#world").append("<article></article>", [$("<a>", {
href: link
}) + ("<h3>" + title + "</h3>")]);
This is what the end result currently is:
<article></article>
[object Object]
<h3>Students Fainting From Hunger in Venezuela’s Failing School System</h3>
And what I want it to become:
<article> <a href= myLink <h3>Students Fainting From Hunger in Venezuela’s Failing School System</h3> </a> </article>
I want to apply my link so that everywhere the user click on the content it goes to the link. Hopefully you can guide me. Thanks!
You can build your article element step by step.
Create 'article' as an element, then create your 'a' element. Append the 'h3' element to the 'a' element before appending 'a' to 'article', and then 'article' to '#world'.
let article = $("<article></article>")
let a = $("<a></a>", {href: link})
a.append("<h3>" + title + "</h3>")
article.append(a)
$("#world").append(article)
You're not using append as described in the documentation -- see the type of arguments you can pass.
Maybe you intended this:
$("#world").append(
$("<article>").append(
$("<a>", { href: link }),
$("<h3>").text(title)
)
);
I have a file which has html code like :
<div>
<ul>
<li>
<span class='hour'>5pm</span>
<span class='temp' data-code='10'></span>
</li>
<li>
<span class='hour'> 7pm</span>
<span class='temp' data-code='8'></span>
</li>
<li>
<span class='hour'> 9pm</span>
<span class='temp' data-code='14'></span>
</li>
</ul>
</div>
The Jquery code:
var url = file;
$.get(
url,
function (data) {
var html = $(data),
hours = html.find('span.hour');
$('.container').html('<p id="hour">'+ hours[0]+'</p>');
}
});
The html that the JS file linked to:
<div class="container"></div>
I get this inserted into the .contaner div : [object HTMLSpanElement]
I want to get the text inside each of the spans with class hour
Also , How can I get the value inside the second div with class temp , Which is data-code?
Check if this is what you are looking for. (Check console)
https://codepen.io/anon/pen/EQQJQL
Code from it
$(function() {
var hourSpans = $('.hour')
hourSpans.each(function() {
console.log($( this ).html());
});
var tempSpans = $('.temp')
tempSpans.each(function() {
console.log($( this ).attr('data-code'));
});
});
You can iterate on span.hour. Use .append() to append <p>..</p> in .container
function(data) {
// Iterate on span.hour
$(data).find('span.hour').each(function() {
$('.container').append('<p id="hour">' + $(this).html() + '</p>');
});
}
I have this HTML code:
<div class="content">
<article class="underline">
<a href="incidente.html"><img id="incidente"
src="img/buraco.jpg" alt="Incidente" /></a>
<h2></h2>
<p id="desc">Esse buraco na rua Montes Claros já está há 1 ano
trazendo transtornos aos moradores</p><p></p>
<div class="date" id="date"></div>
<img class="tick" alt="não resolvido" src="img/no-tick.png">
<img class="apoio" alt="apoiar" src="img/apoio.png">
</article>
And this ajax that receive an array:
$.ajax({
type: "GET",
url: "http://localhost/again/www/index.php",
dataType: "json",
success: function (data) {
var tit = "";
// Loop over each object
for (var $i = 0; $i < data.length; $i++) {
var object = data[$i];
tit+= object.titulo;
}
$('#tit').html(tit);
}
});
</script>
Now, it is inserting everything in the same HTML code(off course,because I don't have a foreach), but I would like to show this HTML for each row(each "tit") that i am receiving...Can someone help me?
What I understand is this: You have an array with text that you want to loop through, and display.
If this was your array:
["Text 1", "Text 2", "Text 3", "Text 4", "Text 5"]
then you want this to be displayed
<element>Text 1</element>
<element>Text 2</element>
<element>Text 3</element>
<element>Text 4</element>
<element>Text 5</element>
The problem in your code
The problem I see in your code is that you are using jquery's .html(arrayItem) which will overwrite any existing text inside of the element.
Instead look at my solution: (http://jsfiddle.net/ProgrammerKid/v6upsLp8/)
HTML
<div id="tit"></div>
JavaScript
$(document).ready(function () {
var tit = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5"];
for (var i in tit) {
var element = document.createElement("h2");
element.innerHTML = tit[i];
$("#tit").append(element);
}
});
over here we use jQuery's .append, and we create a node and we append the node into the wrapper element.
If you have any questions, please leave a comment below and I will reply ASAP
Your best bet to keep things organised is to use a templating engine like handlebars. I've set up a jsfiddle for you that renders out your articles using the example data you provided (which needed a bit of formatting to get working).
http://jsfiddle.net/4ud6rLfq/10/
// This is what you'll need to get the data via AJAX
var source = $("#template").html();
var template = Handlebars.compile(source);
$.ajax({
type: "GET",
url: "http://localhost/again/www/index.php",
dataType: "json",
success: function (data) {
$.each(data, function(key, value) {
$('#articles').append(template(value));
});
}
});
// A demo using the data you provided (formatted a bit)
var data = [
{
"codigo":"32",
"titulo":"Some title here",
"descricao":"Here is my description",
"data":"2015-10-29 21:48:13"
},{
"codigo":"33",
"titulo":"Title here",
"descricao":"description here",
"data":"2015-10-30 20:45:46"
}
];
var source = $("#template").html();
var template = Handlebars.compile(source);
$.each(data, function(key, value) {
$('#articles').append(template(value));
});
And the HTML you'll need:
<script id="template" type="text/x-handlebars-template">
<article class="underline">
<a href="#">
<img class="incidente" src="" alt="{{titulo}}" />
</a>
<h2>{{titulo}}</h2>
<p class="desc">{{descricao}}</p>
<p></p>
<div class="date" class="date">{{data}}</div>
<img class="tick" alt="não resolvido" src="img/no-tick.png">
<img class="apoio" alt="apoiar" src="img/apoio.png">
</article>
</script>
<div id="articles"></div>
There's an example using your $.ajax function commented out and another example below it using the data variable - all you need to do is include handlebars in your page after jQuery and it should be good to go. You can edit the variables in the template to match whatever you pass back to your script via ajax.
Basically what's happening is your setting up the template for your data first, then you loop over your data and bind each item to the template, the item template is then appended to the #articles container as HTML and it moves on to the next item until it's finished.
If I understand you, you have multiple articles and you want to change their titles dynamically?
If so, first of all you should remove;
$('#tit').html(tit);
Then inside the loop put this:
$('#content article:eq('+$i+')').find('#tit').html(object.titulo);
This works only if $i is the same as the elements index relative to their parent.
You can make a function which returns a string with the html-markup. If you need to populate the html-template then you will need to send params to that function. Here is an example of the javascript:
http://jsfiddle.net/fnLjcfvr/1/
function getHtml(title){
var html = "";
html += '<div class="content">';
html += '';
html += '<article class="underline">';
html += '<a href="incidente.html"><img id="incidente"';
html += 'src="img/buraco.jpg" alt="Incidente" /></a>';
html += '<h2> + ' title ' + </h2>';
html += '<p id="desc">Esse buraco na rua Montes Claros já está há 1 ano trazendo transtornos aos moradores</p><p></p>';
html += '<div class="date" id="date"></div>';
html += '<img class="tick" alt="não resolvido" src="img/no-tick.png">';
html += '<img class="apoio" alt="apoiar" src="img/apoio.png">';
html += '';
html += '</article>';
return html;
}