I have here this code:
var photo = place.photos[0].getUrl({ 'maxWidth': 50, 'maxHeight': 50 });
var sideClick = jQuery("<a class=side_click href='#'></a>");
$(sideClick).html(place.name+place.rating);
$("#side_bar").append("<div class='elemenat'><div class='draggable'><img style='margin-left:3px; margin-top:5px;' src="+ photo +" width='46' height='42' /></div><div class='elementname'>").append(sideClick).append("</div></div>");
$(sideClick).on("click", function() {
markers[i].modalWindow_.getDetails(markers[i].place_);
});
}
and this code render:
<div id="side_bar">
<div class="elemenat">
<div class="draggable ui-draggable">
<img style="margin-left:3px; margin-top:5px;" src="https://lh6.googleusercontent.com/-T0_fJX5zza0/UdSnOaucZvI/AAAAAAAAAFc/gQhK3IbHJfY/w50-h50-s0/Small%2BLogo.png" width="46" height="42"></div>
<div class="elementname"></div></div>
<a class="side_click" href="#">James Cook Hotel Grand Chancellor3.6</a>
How I must change js code to render html where <a class="side_click" href="#">James Cook Hotel Grand Chancellor3.6</a> will be into <div class="elementname"></div> so
must be rendered like this:
<div class="elementname">
<a class="side_click" href="#">James Cook Hotel Grand Chancellor3.6</a>
</div>
Don't create elements by raw HTML text. Instead, use jQuery's DOM manipulation capabilities. It makes things much simpler to understand, maintain and less error-prone.
So instead of something like:
var sideClick = jQuery("<a class=side_click href='#'></a>");
$(sideClick).html(place.name + place.rating);
It is better to do:
var sideClick = $("<a>").addClass('side_click').attr('href', '#')
.text(place.name + place.rating);
Besides being easier to structure and spot errors, you also get the added benefit of escaping the place.name + place.rating string.
Check the updated code using this approach (and with the end result you expected):
var photo = place.photos[0].getUrl({
'maxWidth': 50,
'maxHeight': 50
});
var elemenatDiv = $('<div>').addClass('elemenat');
var draggableDiv = $('<div>').addClass('draggable');
var logo = $('<img>').css({'margin-left': '3px', 'margin-top': '5px'})
.attr('src', photo).attr('width', 46).attr('height', 42)
var sideClick = $("<a>").addClass('side_click').attr('href', '#')
.text(place.name + place.rating);
var elementnameDiv = $('<div>').addClass('elementname');
elemenatDiv.append(draggableDiv.append(logo));
elemenatDiv.append(elementnameDiv.append(sideClick));
$("#side_bar").append(elemenatDiv);
$(sideClick).on("click", function () {
markers[i].modalWindow_.getDetails(markers[i].place_);
});
See demo fiddle here.
Append sideclick to the elementname div, not to the side_bar div
var element = $("<div class='elemenat'><div class='draggable'><img style='margin-left:3px; margin-top:5px;' src="+ photo +" width='46' height='42' /></div>");
var elementName = $(<div class='elementname'>);
element.append(elementName);
elementName.append(sideclick);
$("#side_bar").append(element);
Take a look at http://api.jquery.com/category/manipulation/.
You have a couple of different options. You could just change the order in which you append things, use the InsertAfter or InsertBefore methods, or my personal recommendation, putting everything onto the DOM and then using the wrap() function to wrap the side_click link with the div.
Something like
\\append everything
$('.side_click').wrap('<div class="elementname" />');
Related
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 have:
var cnt = '
<img alt="pic1" src="/data/18139/1.jpg" />
<div>
<p>
<img alt="pic2" id="zwei" src="/data/18139/2.jpg" />
</p>
<img alt="pic3" src="/data/18139/3.jpg" />
</div>';
I want to get/set the alt attribute of an img tag by giving the src attribute, no matter how deep the img is.
I tried:
$(cnt).find("img[src$='"+pic+"']").attr('alt'); //can only get the object
$(cnt).filter("img[src$='"+pic+"']").attr('alt') //can only get the alt on the root of thre DOM.
Also tried some combinations and .find(function(... but I simply can´t work it out.
The special thing is, I can not work directly in the DOM. My HTML is stored in the cnt variable. So I´m calling a function like this:
function refreshEditorAlt(src,newalt){
var cnt=getEditorContent();
var newcnt = cnt.replace($("img[src$='"+src+"']", cnt).attr('alt'), newalt);
setEditorContent(newcnt);
}
You can try this code, note that jQuery methods can help you much:
var cnt = '<img alt="pic1" src="/data/18139/1.jpg" /><div><p><img alt="pic2" id="zwei" src="/data/18139/2.jpg" /></p><img alt="pic3" src="/data/18139/3.jpg" /></div>';
var $cnt = $("<div>" + cnt + "</div>");
//input
var src = "/data/18139/1.jpg";
var newAlt = "Xpic";
//update new alt
$cnt.find("img[src$='" + src + "']").attr('alt', newAlt);
//output
cnt = $cnt.html();
$('#out').text(cnt);
Demo.
Note that you should wrap the cnt into some element (such as a <div></div>) so that you can use jQuery to solve your problem.
Try this to get the value:
$(cnt).find("img[src$='"+pic+"']").attr('alt');
Try this to set the value:
$(cnt).find("img[src$='"+pic+"']").attr('alt', newValue);
I think your problem is with the line breaks where you've defined the variable cnt. So instead you want:
var cnt = '<img alt="pic1" src="/data/18139/1.jpg" /><div><p><img alt="pic2" id="zwei" src="/data/18139/2.jpg" /></p><img alt="pic3" src="/data/18139/3.jpg" /></div>';
And then something like this will work:
alert($(cnt).find("img[src$='/data/18139/2.jpg']").attr('alt'));
Obviously you're wanting to pass the value of src into a function or something, but hopefully this should solve your problem.
Quick demo to show it works this way http://jsfiddle.net/4z5Sh/
I need a little help with a Javascript function I am creating. In essence, I need to loop through a set of DIVs with class .DetailRow and find a child DIV's content (inner text). If this text is matched to a variable, then I need to replace this inner text with an IMG HTML statement.
BTW I am kinda new at this (4 months old!) so apologies if the issue is simple, but I have tried a few combos and I am stuck.
Here's the HTML:
<div class="DetailRow" style="display: ">..</div>
<div class="DetailRow" style="display: ">..</div>
<div class="DetailRow" style="display: ">
<div class="Label">Availability:</div>
<div class="Value">in stock + Free Shipping</div>
</div>
Example, if I find "in stock" in the LABEL inner text, I want to replace it with the value of the variable "instock" which is an IMG HTML statement. See my code attempt below.
<script type="text/javascript">
$(window).load(function(){
var instock = '<img src="https://linktoimgfolder/instock.gif" title="Product available, usually ships 24hrs to 48hrs after order receipt" style="margin-top:-3px;">';
var lowstock = '<img src="https://linktoimgfolder/lowstock.gif" title="Product stcok low, order today so you do not miss out">';
var nostock = '<img src="https://linktoimgfolder/outstock.gif" title="Product out of stock, could ship 1 to 2 weeks after order receipt">';
$('div.DetailRow')each(function(){
if (indexOf($(this).childNodes[1].innerHTML, "in stock") > 0) {
$(this).childNodes[2].innerHTML = "";
$(this).childNodes[2].innerHTML = instock;
} else if (indexOf($(this).childNodes[1].innerHTML, "low stock") > 0) {
$(this).childNodes[2].innerHTML = "";
$(this).childNodes[2].innerHTML = lowstock;
} else {
$(this).childNodes[2].innerHTML = "";
$(this).childNodes[2].innerHTML = nostock;
};
});
});
</script>
By the way,m I cannot match text exactly as the text beyond the "+" will change from time to time, thus I am trying indexOf.
Many thanks in advance for your assistance!
M
Using the :contains selector
var stock = {'in stock': instock, 'low stock': lowstock, 'no stock': nostock};
Object.keys(stock).forEach(function(key) {
$('div.DetailRow div:contains(' + key + ')').html(stock[key]);
});
jsFiddle Demo
A pure jQuery solution:
$.each(stock, function(key, value) {
$('div.DetailRow div:contains(' + key + ')').html(value);
});
You have typo in this line $('div.DetailRow')each(function(){ and then you can use jQuery .text() and .html() to check value and update.
Try:
$('div.DetailRow').find("div").each(function(){
if($(this).text().indexOf("in stock")!=-1){
$(this).text("");
$(this).html(instock);
}else if($(this).text().indexOf("low stock")!=-1){
$(this).text("");
$(this).html(lowstock);
}else{
$(this).text("");
$(this).html(nostock);
}
});
DEMO FIDDLE
NOTE: Updated code to find div inside div.DetailsRow. Change it according to your requirement.
I have an 'a href' that is a title.
Vendor1 product title
I want to display an image based on the first word of the title.
Vendor1 product title
<div class="logo"></div>
Vendor2 product title
<div class="logo"></div>
Vendor3 product title
<div class="logo"></div>
These are item cells and they use the same template to be generated so the classes are always the same. There are many of them.
The script I have so far is working but only for the first product in the list (shows correct logo).
function getlogo() {
var string1 = document.getElementsByClassName('title')[0].innerHTML;
var vendor = string1.replace(/([a-z]+) .* ([a-z]+)/i, "$1").toLowerCase();
document.getElementsByClassName('logo')[0].innerHTML = '<img src="/myimages/' + vendor + '.jpg" width="100px" height="50px" onerror="imgError(this);">';
function imgError(image) {
image.onerror = "";
image.src = "default.jpg";
return true;
}
}
getlogo();
I've looked around but sure how to loop this or even if that is the solution.
http://jsfiddle.net/W7bm5/
It's easy if you use jQuery each function.
function imgError(image) {
image.onerror = "";
image.src = "default.jpg";
return true;
}
$(document).ready(function() {
$(".title").each(function() {
var string1 = $(this).text();
var vendor = string1.replace(/([a-z]+) .* ([a-z]+)/i, "$1").toLowerCase();
$(this).html('<img src="/myimages/' + vendor + '.jpg" width="100px" height="50px" onerror="imgError(this);">');
});
});
or you can do it with the pure javascript, but put your logics in a loop, with [0] replaced to the loop index.
Update - here's how to keep the current text links:
function imgError(image) {
image.onerror = "";
image.src = "default.jpg";
return true;
}
$(document).ready(function() {
$(".title").each(function() {
var string1 = $(this).text();
var vendor = string1.replace(/([a-z]+) .* ([a-z]+)/i, "$1").toLowerCase();
var html = $(this).parent().html();
$(this).parent().html(html + '<br /><img src="/myimages/' + vendor + '.jpg" width="100px" height="50px" onerror="imgError(this);">');
});
});
You could use a for loop to run through the code you have for a different index of the getElementsByClassName results. See your jsFiddle
You could also ditch the getElementByClassName, which I think has spotty support in some browsers and isn't especially good performance, and navigate the DOM using JavaScript if your structure is always the same, or even jQuery if you'd like a library to make it easier.
But by far the best is if you did it when it was generated in the first place. How are you generating the code and could you not use that to achieve what you are trying to achieve?
I'm trying to learn HTML and Javascript/jQuery. If I have a container which holds a title, an image, a description and a number, then I want to create a new container with the exact same format (except the values will be different), how is this commonly done?
This is an example of the format I'm looking for in each item.
<li>
<div>
<div>
Image Name
</div>
<div>
<a href=URL>
<img src='image_url'>
</a>
</div>
<div>
Description
</div>
<div>
num_comment Comments
</div>
</div>
</li>
Do I just create a string and concatenate with the actual values for the image, then add that string to some variable I've saved called html_content, and then set the html value to html_content? Is that the common way of doing this or is there a better way?
EDIT
To give a better idea of what I'm currently doing, here's the javascript:
var html1 = '<li><div><div>';
var html2 = '</div><div><a href="';
var html3 = '"><img src="';
var html4 = '"></a></div><div>';
var html5 = '</div><div>';
var html6 = '</div></div></li>';
function render(pics){
for (var i in pics){
html = html + html1 + pics[i].name + html2 + pics[i].image_url + html3 + ...
};
$('pics').html(html);
}
In jQuery you just have to use the append() function to add on to something.
You could do something like...
$('select element').append('<li><div>....etc.');
and where you want a different value you can use a variable.
You can use .clone() and create a copy of this, then iterate through the cloned object and change what you need:
var $objClone = $("li").clone(true);
$objClone.find("*").each(function() {
//iterates over every element. customize this to find elements you need.
});
To change the image source you can do:
$objClone.find("img").attr("src", "new/img/here.jpg");
Fiddle demoing the concept: http://jsfiddle.net/H9DnA/1/
You may find it useful to explore some of the JavaScript templating libraries. The essential idea is that you create a template of your markup:
<li>
<div>
<div>
{{name}}
</div>
<div>
<a href="{{url}}">
<img src="{{imageUrl}}">
</a>
</div>
<div>
{{description}}
</div>
<div>
{{comments}}
</div>
</div>
</li>
Then you merge it against some associated matching object and insert it into your document:
{ name: 'Image Name',
url: 'http://example.com',
imageUrl: 'http://example.com/image.jpg',
description: 'Description',
comments [ { text: 'Comment' } ]
}
function render(pics)
{
var theList = document.getElementByid("LIST ID");
for (var i in pics){
var listItem = document.createElement('li'); // Create new list item
var nameDiv = document.createElement('div'); // Create name DIV element
nameDiv.innerHTML = pics[i].name; // Insert the name in the div
var img = document.createElement('img'); // Create Img element
img.setAttribute('src',pics[i].src); // Assign the src attribute of your img
var imgDiv = document.createElement('div'); // Create Img Div that contains your img
imgDiv.appendChild(img); // Puts img inside the img DIV container
var descDiv = document.createElement('div'); // Create Description DIV
descDiv.innerHTML = pics[i].description; // Insert your description
listItem.appendChild(nameDiv); // Insert all of you DIVs
listItem.appendChild(imgDiv); // inside your list item
listItem.appendChild(descDiv); // with appropriate order.
theList.appendChild(listItem); // Insert the list item inside your list.
}
}
I think this will work just fine:
$('#button').click(function () {
var html1 = '<li><div><div>';
var html2 = '</div><div><a href="';
var html3 = '"><img src="';
var html4 = '"></a></div><div>';
var html5 = '</div><div>';
var html6 = '</div></div></li>';
function render(pics){
for (var i in pics){
html = html + html1 + pics[i].name + html2 + pics[i].image_url + html3 + ...
$("ul").append(html);
}
}
// call render
});
I didn't do a test run on your code so there might be an error somewhere. My tweak adds this line $("ul").append(html); inside your loop