So I see here how to add a div and here how to add a class but I'm having trouble combining the two. I want to generate a whole bunch of div's with a specific class and id within the div sparkLineContainer.
I have the containing div
<div id="#sparkLineContainer"></div>
and I want to add a bunch of the following to it
<div id="#sparkLineContainer">
<div class="sparkLines" id="id1">Some stuff here</div>
<div class="sparkLines" id="id2">Some stuff here</div>
<div class="sparkLines" id="id3">Some stuff here</div>
// and so on
</div>
snippet - I didn't make it very far, I'm stumped
$('#sparkContainer').add("div"); \\ How do I add the id and class to this div?
\\ And as a repeat the function will it overwrite this?
The function I'm trying to do this with.
function renderSparklines (array1, sparkLineName, id) {
// array1 is the data for the spark line
// sparkLineName is the name of the data.
// Turn all array values into integers
arrayStringToInt(array1);
// Create new div of class sparkLines
$('#sparkContainer').add("div")
// Render new spark line to
$('.sparkLines').sparkline(array1, {width:'90px'});
var htmlString = ""; // Content to be added to new div
// GENERATE LITTLE SPARK BOX
htmlString +=
'<font class = "blueDescriptor">' + sparkLineName + '</font>'+
'<br>'+
'<font class = "greyDescriptorSmall">Ship to Shore</font>'+
'<br>'+
'<font class = "blackDescriptorSparkLine">' + array1[array1.length-1] + '</font>'+
'<font class = "greenDescriptorSparkline">(' + (array1[array1.length-1] - array1[array1.length-2]) + ')</font>' +
'<br>';
$('.sparkLines').prepend(htmlString);
}
add does not do what you think it does. You are looking for append or something similar.
You can create the div first and define its attributes and contents, then append it:
var $newDiv = $("<div/>") // creates a div element
.attr("id", "someID") // adds the id
.addClass("someClass") // add a class
.html("<div>stuff here</div>");
$("#somecontainer").append($newDiv);
You need .append or .prepend to add a div to the container. See my version below,
var $sparkLines = $('.sparkLines');
$("#sparkLineContainer")
.append('<div id="id' +
($sparkLines.length + 1) +
'" class="sparkLines">Some Stuff Here</div>')
Also I noticed that you have id of the div as #sparkLineContainer. You should change it as below,
<div id="sparkLineContainer">
...
DEMO
You can add a div or any other tag along with class like:
$('<div/>',{ class : 'example'}).appendTo("p");
Probably the easiest way is to just modify the innerHTML:
$("#sparkLineContainer").append('<div class="sparkLine" id="id1"></div>');
There's other ways as well, but this is the method I generally use.
Related
I Know I can do this with static HTML, but I want to create dynamically, and I am struggling a lot.
Here is what I want to do:
I have 2 divs.
<div class="TxtTile">
</div>
<div class="pInfo">
</div>
Inside each div I want to have several paragraphs. Let's say 10, in each div.
The first div with class "TxtTile" i want to have the title of something, let's say titles like, age,country,experience,street etc.In the other div with class 'pInfo' I want to contain the information that corresponds with TxTtitle.
Like, age 25, experience 10 years etc, that will be taken from local Storage, where I already have it set up. This two divs will be next to each other, which I have already done with css.
For example.
Left side
<div class="TxtTile"> `<div class="pInfo">
<p class="styleforP"> <p class="styleforP">
Age 25
</p>
</p>
</div> </div>`
I would be happy if I can make this with native js.
There are two ways you can do this:
1) you can create an element and keep appending to its place
First get div element inside which you want to create new element, Here rather than having a class i would prefer to have id based selection of the element
var element = document.querySelector('.TxtTile');
Create a p element and add class to it, you can similarly add content inside it aswell
var pElem = document.createElement('p');
pElem.className = 'styleforP';
pElem.innerHTML = 'Age';
Append that created element inside your div
element.appendChild(pElem);
2) Create an HTML template pass your values to that template and create innerHTML and directly put that innerHTML into your parent element
var item = {
name: "My Name",
age: 30,
other: "Other Info"
}
var template = [];
template.push(
'<div class="row">',
'<span class="name-info">' + item.name + '</span>',
'<span class="age-info">' + item.age + '</span>',
'<span class="other-info">' + item.other + '</span>',
'</div>'
);
var htmlString = template.join('');
var element = document.querySelector('.TxtTile');
element.innerHTML = htmlString;
If you are going to add a lot of items then second approach is a lot better, as creating single element and appending them to DOM tree is quite slow, then passing whole HTML string.
var myData = {
title: "My title",
info: 25
};
// Store references to the wrapper elements
// The first element that has this class, or null if there aren't any
var titleWrapper = document.querySelector(".js-titleWrapper");
var infoWrapper = document.querySelector(".js-infoWrapper");
// Create the paragraph elements
var titleP = document.createElement("p");
var infoP = document.createElement("p");
// Add classes
titleP.classList.add("styleForP");
infoP.classList.add("styleForP");
// Add the text
titleP.innerText = myData.title;
infoP.innerText = myData.info;
// Add the paragraphs to their wrappers
titleWrapper.appendChild(titleP);
infoWrapper.appendChild(infoP);
<div class="TxtTile js-titleWrapper">
</div>
<div class="pInfo js-infoWrapper">
</div>
i think this is a bad idea for doing this if you have multiple records then you cant handle by querySlector.
good idea is create a parent element like this
<div id="parent"></div>
then get this element by javascript and then append this element with your dynamic records like this
var parentEle = document.getElementById("parent");
apply loop if records are multiple
var child = Document.createElement("div");
child.innerHTML = "<div class='TxtTile'>age</div><div class='pInfo'>25</div>";
parentEle.appendChild(child);
I am building html on the fly need to add data before I add it to DOM. Since I am looping thru' lot of information, I would like to add the relevant data info along with the dom I am building instead of adding the html and then looping thru again to add the data.
result.forEach(function(record) {
html += '<div id ="' record.ID + '">test content </div> ';
//add data to above
});
I can do another loop here after adding it to DOM
$(body).append(html);
testresult.forEach(function(record) {
$("#" +record.ID).data(record);
});
Instead of concatenating strings to piece together your HTML, you may way to try something like this:
result.forEach(function(record) {
$('.selector').append(function () {
var $div = $('<div></div>');
$div.attr('id', record.testID).text('some text');
return $div;
});
});
This creates a new div jquery object for each item in result. You can use the record object to add attributes, data, text, etc to you object. It will be added the DOM when the callback passed into .append returns your new jquery DOM object.
Start trying to use jQuery to create your html elements so you can take fully advantage of jQuery and its plugins.
Ex:
var div = $("<div></div>") // create the element
.text("test content") // change the inner text
.attr("id", record.testID); // set the element id
div.appendTo("body");
You can check out [http://www.w3schools.com/jquery/] as a great source for learning jQuery.
You have quotes problem in the following line :
html += '<div id =record.testID' + '>test content </div> ';
________^______________________^___^_____________________^
You should fix that using double quotes because as it's now the string will be considered as '<div id =record.testID'.
html += '<div id="'+record.testID+'">test content </div>';
Or you could use separated definition :
$.each(result, function(index,record) {
var div = $('<div>test content</div>');
div.attr('id', record.testID);
div.data('test', record.testDATA);
$('body').append(div);
})
Hope this helps.
var result = [{testID: 1,testDATA: 'data 1'},{testID: 2,testDATA: 'data 2'},{testID: 3,testDATA: 'data 3'}]
var html='';
$.each(result, function(index,record) {
var div = $('<div>test content</div>');
div.attr('id', record.testID);
div.data('test', record.testDATA);
console.log(div.data('test'));
$('body').append(div);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I need a suggestion on below scenario.
I have an object of items and dynamically building a html object as follows:
$.each(item,function(k, iteminner) {
html += '<td><div id="outerdiv">' + iteminner.Name + '</div>';
html += '<div id="clickme"></div></td>';
});
A table is built in this format, where each box will contain a name and button in each td. When a user clicks on a button of a cell I want to show the name respectively.What is it that I am missing here?
$('#clickme").click() {
alert($("#outerdiv").iteminner.name);
}
Assuming that id is unique for both the divs, like id="outerdiv" + k , how do I access element present in second cell, when second div id="clickme" + 2 is clicked?
ID's they have to UNIQUE
// Use class instead
$.each(item, function(k, iteminner) {
html += '<td><div class="outerdiv">' + iteminner.Name + '</div>';
html += '<div class="clickme"></div></td>';
});
// You need to have event delegation here as a direct onclick wont be binded for the dynamically created .clickme
$(document).on("click", ".clickme", function(){
// You need to fetch the html of .outerdiv, so traverse to it first.
var _html = $(this).closest("td").find(".outerdiv").html();
alert(_html);
});
Firstly you are appending multiple elements with the same id to the DOM, which is invalid. You should change your HTML to use classes, like this:
$.each(item, function(k, iteminner) {
html += '<td><div class="outerdiv">' + iteminner.Name + '</div><div class="clickme"></div></td>';
});
From there you need to use a delegated event handler on the .clickme elements (as they are dynamically created after the DOM has loaded) to traverse the DOM and find their sibling .outerdiv. Try this:
$(document).on('click', '.clickme', function() {
var name = $(this).siblings('.outerdiv').text();
// do something with name here...
});
Note that I used document as the primary selector above. Ideally you should use the nearest static parent element - I would suggest you use the same selector you use to append the html variable to.
Is it possible to get all colorvalues that exist in a div with a certain class, and its child elements?
for example, i have:
<div class="row client">
Link1
<span style="color:#f3f3f3;">Span</span>
<h3 style="color:#ff00ff;">Subtitle</h3>
</div>
I want an array to get all colors:
background of the parent div
color of the <a> element
color of the <span> element
color of the <h3> element
Also, i'm using highcharts to display charts in the same div. Is it possible to get the colors used there aswell?
I don't think i can put this any clearer for you guys,
Many thanks!
Job
You can use:
var colorarray=[];
$('.client').children().addBack().each(function(){
if(!$(this).is('.client'))
colorarray.push("color of the <" +$(this).prop("tagName")+"> is "+ $(this).css('color'))
else
colorarray.push("background of <" +$(this).prop("tagName")+"> is "+ $(this).css('backgroundColor'))
})
Working Demo
If you want the color in hex, you can refer this https://stackoverflow.com/a/1740716/1719752
You can just loop through all the elements in the div
Fiddle
var elements = $(".client").children()
$(elements).each(function(index) {
console.log( index + ": " + $(this).css("color"));
});
Here’s a rather inefficient but, I think, easy to understand approach without libraries:
let allNodes = Array.from(document.querySelectorAll('*'));
let setOfColors = allNodes.reduce((colors,el) => {
return colors.add(getComputedStyle(el).backgroundColor)
}, new Set)
let arrayOfColors = Array.from(setOfColors);
I'm stuck. I have two sets of dynamic elements with a common class (zone and box) and a dynamic class:
<span class="zone dynamicClass1 clickable">Text</span>
<span class="zone dynamicClass6-2 clickable">Text</span>
<div class="box dynamicClass6-2"></div>
<div class="box dynamicClass1"></div>
When you mouseover the <span> "zone", I want to add a class to the <div> "box". Then on mouseleave I want the class to be removed. Thus, something like:
$(document).on("mouseenter",".zone",function(){
$(this + ".the dynamic class").find(".box.the same dynamic class").addClass("hovered");
}).on("mouseleave",".zone",function(){
$(".box.the found dynamic class").removeClass("hovered");
});
The dynamic classes have to be retrieved from the hovered element and then used in finding its match, they cannot be programmed by name. Any help would be great.
The way you have it setup right now, you search for the div inside the span. What you want to do is get the class and then find the according div. I would suggest moving the common class to either an id data attribute, so you can do this:
<span class="zone clickable" id="dynamicClass1">Text</span>
<span class="zone clickable" id="dynamicClass6-2" >Text</span>
var currentClass = $(this).attr("id");
$("div." + currentClass).addClass("hovered");
or this:
<span class="zone clickable" data-class="dynamicClass1">Text</span>
<span class="zone clickable" data-class="dynamicClass6-2" >Text</span>
var currentClass = $(this).data("class");
$("div." + currentClass).addClass("hovered");
See this JSFiddle: http://jsfiddle.net/7v3hd/1/
DEMO
$(document).on("mouseenter",".zone",function(){
var $that = $(this),
classes = $that.attr('class'),
// this is the meat here
// you need to do a string manipulation
// to get the dynamic class out of the
// class attribute. You could also do this
// with regex, or split.
theDynamicClass = classes.replace('zone', '').replace('clickable', '').trim(),
$boxWithSameClass = $(".box."+theDynamicClass);
$boxWithSameClass.addClass("hovered");
$that.one("mouseleave",function(){
$boxWithSameClass.removeClass("hovered");
});
});
You can use;
$(document).on("mouseenter",".zone",function(){
var classes = $(this).attr("class").split(" ");
$("div." + classes[1]).addClass("hovered");
}).on("mouseleave",".zone",function(){
var classes = $(this).attr("class").split(" ");
$("div." + classes[1]).removeClass("hovered");
});
HEre is a working demo: jsfiddle