Add svg fill patterns dynamically via JavaScript [duplicate] - javascript

When prepending or appending to an element, it literally puts the text and doesn't compile in HTML:
var banner ={
'Format': '90x120cm',
'Value': 35
};
// var premium = { key: values };
function defineProduct(data) {
var item = $('span.tooltip')[0];
console.log($('span.tooltip'));
for(var keys in data){
console.log(keys);
item.append('<div class="item"><div class="left">'+keys+':</div><div class="right ">'+data[keys]+'</div></div>');
}
}
defineProduct(banner);
HTML:
<div class="three-columns">
<div class="col">
<div class="image-holder">
<a href='' id="premium" class="tooltips">
<img src="" class="premium-img" width="85px" height="79px">
<p class="description">Cartão <br><span style="color: #ffc600;" class="different">premium</span></p>
<span class="tooltip"></span>
</a>
</div>
<!-- Same thing from above different description -->
<!-- ditto -->
</div>
Output:
What have I tried/used:
.get();
.prepend(string);
.html(string);
.text(string); <– I don't know why, but I did
document.createTextNode(string);
set a variable which contains HTML tags strings and set to one of the previous attempts
And the reason I used .get() is because I have more than one object that are equivalent to the quantity of their elements, in this case, I have 3. So, for every append, I have different information. E.g.: .get(0), .get(1), etc

Instead of
item.append....
you can use:
item.insertAdjacentHTML('beforeend',....
insertAdjacentHTML: parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.
var banner = {
'Format': '90x120cm',
'Value': 35
};
function defineProduct(data) {
var item = $('span.tooltip')[0];
//console.log($('span.tooltip'));
for (var keys in data) {
//console.log(keys);
item.insertAdjacentHTML('beforeend', '<div class="item"><div class="left">' + keys + ':</div><div class="right ">' + data[keys] + '</div></div>');
}
}
defineProduct(banner);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="three-columns">
<div class="col">
<div class="image-holder">
<a href='' id="premium" class="tooltips">
<img src="" class="premium-img" width="85px" height="79px">
<p class="description">Cartão <br><span style="color: #ffc600;" class="different">premium</span></p>
<span class="tooltip"></span>
</a>
</div>
<!-- Same thing from above different description -->
<!-- ditto -->
</div>
</div>

You're using ParentNode.append to append a literal DOMString which is appended as a text node instead of jQuery#append here:
var item = $('span.tooltip')[0];
The [0] access the underlying DOM element in the jQuery object. Remove the [0] to use jQuery methods (or eq(0) for the first element in the selection collection as a jQuery object) on it or use Node.appendChild.

[0] needs to be removed from $('span.tooltip')[0] . It is trying to access first child of ".tooltip" span which is not available in DOM.

Related

Copy HTML from element, replace text with jQuery, then append to element

I am trying to create portlets on my website which are generated when a user inputs a number and clicks a button.
I have the HTML in a script tag (that way it's invisible). I am able to clone the HTML contents of the script tag and append it to the necessary element without issue. My problem is, I cannot seem to modify the text inside the template before appending it.
This is a super simplified version of what I'd like to do. I'm just trying to get parts of it working properly before building it up more.
Here is the script tag with the template:
var p = $("#tpl_dashboard_portlet").html();
var h = document.createElement('div');
$(h).html(p);
$(h).find('div.m-portlet').data('s', s);
$(h).find('[data-key="number"]').val(s);
$(h).find('[data-key="name"]').val("TEST");
console.log(h);
console.log($(h).html());
console.log(s);
$("div.m-content").append($(h).html());
<script id="tpl_dashboard_portlet" type="text/html">
<!--begin::Portlet-->
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<span data-key="number"></span> [<span data-key="name"></span>]
</h3>
</div>
</div>
<div class="m-portlet__head-tools">
<ul class="m-portlet_nav">
<li class="m-portlet__nav-item">
<i class="la la-close"></i>
</li>
</ul>
</div>
</div>
<!--begin::Form-->
<div class="m-portlet__body">
Found! <span data-key="number"></span> [<span data-key="name"></span>]
</div>
</div>
<!--end::Portlet-->
</script>
I'm not sure what I'm doing wrong here. I've tried using .each as well with no luck. Both leave the value of the span tags empty.
(I've removed some of the script, but the variable s does have a value on it)
You have two issues here. Firstly, every time you call $(h) you're creating a new jQuery object from the original template HTML. As such any and all previous changes you made are lost. You need to create the jQuery object from the template HTML once, then make all changes to that object.
Secondly, the span elements you select by data-key attribute do not have value properties to change, you instead need to set their text(). Try this:
var s = 'foo';
var p = $("#tpl_dashboard_portlet").html();
var $h = $('<div />');
$h.html(p);
$h.find('div.m-portlet').data('s', s);
$h.find('[data-key="number"]').text(s);
$h.find('[data-key="name"]').text("TEST");
$("div.m-content").append($h.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="tpl_dashboard_portlet" type="text/html">
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<span data-key="number"></span> [<span data-key="name"></span>]
</h3>
</div>
</div>
<div class="m-portlet__head-tools">
<ul class="m-portlet_nav">
<li class="m-portlet__nav-item">
<i class="la la-close"></i>
</li>
</ul>
</div>
</div>
<div class="m-portlet__body">
Found! <span data-key="number"></span> [<span data-key="name"></span>]
</div>
</div>
</script>
<div class="m-content"></div>
In my case only this is working:
var template = $('template').clone(true, true); // Copies all data and events
var $h = $('<div />');
$h.html(template);
$h.find('.input-name').attr('value', "your value here"); // Note: .val("your value here") is not working
$('.list').prepend($h.html());

Unable to access descendant of an HTML element using jQuery

I have a problem with getting a html() value of child of a parent :D
function voteup(e){
var count = $(e).parents('.item').children('.count');
console.log(count.html()); // undefined
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="post_contain">
<img src="images/comments/dQ6dz.jpg" alt="">
</div>
<div class="item">
<p class="post-meta">
<span href="/gag/agVzE1g" target="_blank">
<span class="count">5</span>points
</span>
</p>
<div class="vote">
<ul class="btn-vote left">
<li class="badge-item-vote-up-li">
<a onclick="voteup(this)">Click me</a>
</li>
</ul>
</div>
</div>
In the function voteup(e), I need to get the value of the class 'count', but I don't retrieve the value with html()
children only traverses a single level of the DOM tree - i.e. it won't find grandchildren.
Instead, use closest to find the .item -- which finds the single nearest match, as opposed to parents which can find multiple -- and find to locate the child, since that will traverse arbitrarily deep HTML structures:
function voteup(e){
var count = $(e).closest('.item').find('.count');
alert(count.html());
var actual = parseInt(count.html(), 10);
count.text(actual + 1);
}

How to get data value of a div that has no ID?

Below is part of some code on an html page that lists shopping cart products. Using JavaScript/jQuery, I need to be able to loop through the li items and get the div "data-" values for each. The issue that I am having is that there are no IDs for the div that has the data- value (). I only see the div for "CategoryContent".
<div class="Block CategoryContent Moveable Panel" id="CategoryContent">
<ul class="ProductList ">
<li class="Odd">
<div class="ProductImage QuickView" data-product="577">
<img src="http://cdn3.example.com/products/577/images/1731/2311-.jpg?c=2" alt="Sweater Vest V-Neck Cotton" />
</div>
<div class="ProductDetails">
Sweater Vest V-Neck Cotton
</div>
<em class="p-price">$45.04</em>
<div class="ProductPriceRating">
<span class="Rating Rating0">
<img src="http://cdn3.example.com/templates/custom/images/IcoRating0.png?t=" alt="" style="" />
</span>
</div>
<div class="ProductActionAdd" style="display:;">
Choose Options
</div>
</li>
</ul>
</form>
</div>
So, there is only one li item here, on a typical page, there are up to 9. My goal is to use JavaScript to get the data-product values and then use that to look up a better image thumbnail and have it replaced. So, how do I get the value set for data-product?
Quite easy:
// Loop through all list items of ul.ProductList:
$("ul.ProductList li").each(function (index, element) {
// Find the element with attribute data-product:
$dp = $(element).find("[data-product]");
// Get the value of attribute data-product:
var product = $dp.attr("data-product");
// Now set the high quality thumbnail url:
var url = "/images/hq/" + product + ".png"; // Note that this is just an example
// Here you can use $(element) to access to current li (and the img):
$(element).find('.ProductImage img').attr('src', url);
});
You can use this:
$("#CategoryContent div[data-product]").each(function(){
alert($(this).attr('data-product'));
});
Pure JS:
var divs = document.querySelectorAll('#CategoryContent div[data-product]');
var index = 0, length = divs.length, prodIds = [];
for ( ; index < length; index++) {
prodIds.push(divs[index].getAttribute('data-product'));
}
Fiddle: http://jsfiddle.net/we5q7omg/
You could use the class name to get the data-product
var products = document.getElementsByClassName("ProductImage");
for(var i=0; i<products.length;i++)
{
console.log(products[i].getAttribute("data-product"));
}
Using JQuery, you can get the elements with the data-product attribute by simply calling
$('[data-product]')
// Or if you only want the data-product elements within the UL.
$('ul').find('[data-product]')
From there you can simply do pull the products from the elements. For Example:
var products = $('[data-product]').map(function() {
return $(this).data('product');
});

Grabbing number from selected class based on string match

I need to grab the number between [ and ] within the selected class of an li list, and store the number in a variable. I've tried the following, but I'm missing something. I'm not sure of the regex required to look between brackets and grab a string.
Javascript
var assetID = $(".selected:contains('on-air-date').find('[]');
HTML
<ul id="asset-list" class="expandable selectable normal" style="height: 671px;">
<li class="selected">
<div class="thumb">
<a href="/content/assets/750">
<img src="https://www.google.com/images/srpr/logo11w.png">
</a>
</div>
<div class="title">
<div>
<strong>Title of story</strong>
<br>
<span class="on-air-date">
On air: 10/28/14 05:30:00pm
[750]
</span>
<br>
<span class="blue radius label">Staging</span>
<span class="green radius label">Live</span>
</div>
</div>
</li>
<li>
<div class="thumb">
<a href="/content/assets/4200">
<img src="https://www.google.com/images/srpr/logo11w.png">
</a>
</div>
<div class="title">
<div>
<strong>Another story title</strong>
<br>
<span class="on-air-date">
On air: 12/10/14 02:09:18pm
[4200]
</span>
<br>
<span class="blue radius label">type label</span>
</div>
</div>
</li>
<li>
<div class="thumb">
<a href="/content/assets/4201">
<img src="https://www.google.com/images/srpr/logo11w.png">
</a>
</div>
<div class="title">
<div>
<strong>Yet another story title</strong>
<br>
<span class="on-air-date">
On air: 12/10/14 02:09:18pm
[4201]
</span>
<br>
<span class="blue radius label">type label</span>
</div>
</div>
</li>
</ul>
JSFiddle: link
Your current code is invalid, as :contains is used to look for a text value within an element, not a class. You need to use find() and text() to retrieve the value in the element. From there you can use a regular expression to extract the value in the braces. Try this:
var selectedAirDateText = $('.selected').find('.on-air-date').text();
var matches = /\[(.+)\]/gi.exec(selectedAirDateText);
console.log(matches[1]); // = '750'
Example fiddle
A regular expression can help you get the number as follows:
var num = $('.selected span.on-air-date').text().replace(/[^\[]*\[(\d+)\].*/,'$1');
Demo
:contains('on-air-date') not valid, you cannot use contains to access the child elements with the specified class. Also .find('[]') not valid. The following code worked for me:
$('.selected').click(function () {
var assetID = $(this).find('.on-air-date').text().split('[')[1].replace(']', '');
//this first splits the text into two by '['
//then we get the second half by [1]
//finally we remove the last character ']' by using .replace
alert(assetID);
})
Demo: https://jsfiddle.net/k3keq3vL/1/
You'll need to first get the single item you need or run an $.each to get all in the page.
//run the each statement
$(".on-air-date").each(function(index,value) {
//set the string (str) variable to the value's text which is inside the <span>
var str = $(value).text();
// match the string with [ ] with anything inside. and then remove the last ]. Then take the substring of the content after the [
var value = str.match(/\[(.*?)\]/g)[0].replace(/\]/g,'').substring(1,str.length-1));
});
http://jsfiddle.net/k3keq3vL/8/
Open your console to see the list of numbers returned in the console.log of the string match and substring

Get specific data from page and write it to div

I'm building an online store with javascript shopping cart. However, the script doesn't allow printing only one or two values when displaying cart, but I need to do this.
Here's what the cart looks like:
<div class="simpleCart_items">
<div>
<div class="headerRow">
<div class="item-name">Tuote</div>
<div class="item-price">Hinta</div>
<div class="item-decrement">-</div>
<div class="item-quantity">Määrä</div>
<div class="item-increment">+</div>
<div class="item-total">Yhteensä</div>
<div class="item-remove">Poista</div>
</div>
<div class="itemRow row-0 odd" id="cartItem_SCI-1">
<div class="item-name">Teipit</div>
<div class="item-price">€0.00</div>
<div class="item-decrement"><img src="css/minus.png" alt="minus">
</div>
<div class="item-quantity">3</div>
<div class="item-increment"><img src="css/plus.png" alt="plus">
</div>
<div class="item-total">€0.00</div>
<div class="item-remove"><img src="css/remove.png" alt="Remove">
</div>
</div>
<div class="itemRow row-1 even" id="cartItem_SCI-3">
<div class="item-name">Car Speaker -hajuste</div>
<div class="item-price">€4.00</div>
<div class="item-decrement"><img src="css/minus.png" alt="minus">
</div>
<div class="item-quantity">1</div>
<div class="item-increment"><img src="css/plus.png" alt="plus">
</div>
<div class="item-total">€4.00</div>
<div class="item-remove"><img src="css/remove.png" alt="Remove">
</div>
</div>
<div class="itemRow row-2 odd" id="cartItem_SCI-5">
<div class="item-name">Teipit (Musta hiilikuitu)</div>
<div class="item-price">€0.00</div>
<div class="item-decrement"><img src="css/minus.png" alt="minus">
</div>
<div class="item-quantity">1</div>
<div class="item-increment"><img src="css/plus.png" alt="plus">
</div>
<div class="item-total">€0.00</div>
<div class="item-remove"><img src="css/remove.png" alt="Remove">
</div>
</div>
</div>
</div>
NOTE: The cart is written via javascript so it isn't visible in page source, only in inspect mode of the browser.
So how would I gather the item-name, item-priceand item-quantity?
I've tried this:
var name = $('.item-name');
var price = $('.item-price');
var quantity = $('.item-quantity');
var data = name + price + quantity;
$('#items').html(data);
But this won't actually do anything.
When doing this -> $('.item-name');
You are just capturing the element as object but not the value.
Now that you got your element as object, you need to extract the value and, in this case, your element object is a div so you can try .text() or .html() (to get the text or html inside the div).
(For this situation I will use text() cause you are working just with values and there is nothing related to html)
Try this:
var name = $('.item-name');
var price = $('.item-price');
var quantity = $('.item-quantity');
var data = name.text() + price.text() + quantity.text();
$('#items').html(data);
Better solution:
This will make clickable the div in which you have the product and match the cartItem_SCI pattern.
So, when user clicks any of the elements of your cart, you will get the name, price and quantity values that will be attached to the $('#items') div using append() method instead of html() (because using this will replace the product information each time the user clicks a div)
$(document).ready(function() {
$('div[id^="cartItem_SCI-"]').css({ cursor:'pointer' });
$('div[id^="cartItem_SCI-"]').click(function() {
var name = $(this).find('.item-name');
var price = $(this).find('.item-price');
var quantity = $(this).find('.item-quantity');
var data = name.text() + ' - ' + price.text() + ' - ' + quantity.text();
$('#items').append(data + '<br/>');
});
});​
You are just getting a reference to the class, add .html() to get the inner html of the element that the class applied to.
var name = $('.item-name').html();
For one item you can get like this.But since you have multiple items make one object like this .
var item={};
$('.item-name').each(function(){item.name=$(this).html()});
$('.item-price').each(function(){item.price=$(this).html()});
$('.item-quantity').each(function(){item.quantity=$(this).html()});
var data='';
for(var i=0;i<item.length;i++)
{
data+=item[i].name+item[i].price+item[i].quantity;
}
$('#items').html(data);

Categories