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);
Related
I want to insert some unknown HTML (contentToInsert) and remove it later at some point.
If I use insertAdjacentHTML, I cannot later say
myDiv.insertAdjacentHTML('afterbegin', contentToInsert);
myDiv.querySelector('contentToInsert') //cannot work of course
because this does not have id or classname.
I cannot wrap it like this (so I have reference to it later):
var content = document.createElement('div');
content.classList.add('my-content-wrap')
content.innerHTML = contentToInsert;
myDiv.insertAdjacentHTML('afterbegin', adContent);//it can be any allowed position, not just afterbegin
Basically I want to remove it later at some point but dont know how to select it. I dont know the position in which this is going to be instered.
Since insertAdjacentHTML only accepts a string you can
Define your content as a string
Use a template/string to add it
Add that string to myDiv.
Then you can target myDiv again with a selector pointed at that element with the my-content-wrap class, and remove it from the DOM.
const myDiv = document.querySelector('#myDiv');
const content = 'Disappears after two seconds';
const html = `<div class="my-content-wrap">${content}</div>`;
myDiv.insertAdjacentHTML('afterbegin', html);
const pickup = myDiv.querySelector('.my-content-wrap');
setTimeout(() => pickup.remove(), 2000);
<div id="myDiv">Original content</div>
You said "I want to insert some unknown HTML (contentToInsert) and remove it later at some point"
I wouldn't use insertAdjacentHTML at all. Here's how you can achieve it:
let myDiv = document.getElementById('myDiv');
let contentToInsert = "<h1>Some html content</h1>";
myDiv.innerHTML = contentToInsert;
This will insert your content into your div. And you can remove it with:
myDiv.innerHTML = "";
in one of the cases...
const
divElm = document.querySelector('#div-elm')
, Insert_1 = '<span>inserted content 1 </span>'
, Insert_2 = '<span>inserted content 2 </span>'
;
divElm.insertAdjacentHTML('afterbegin', Insert_1);
const ref_1 = divElm.firstChild;
divElm.insertAdjacentHTML('afterbegin', Insert_2);
const ref_2 = divElm.firstChild;
ref_1.classList.add('RED')
ref_2.classList.add('BLU')
console.log( '', ref_1, `\n`, ref_2 )
.RED { color: red; }
.BLU { color: blue; }
<div id="div-elm">
blah blah bla..
</div>
many amazing people already answered your question but here's a workaround, if you're only Adding this specific html using js and other content is preadded in html it's always gonna be the first child as you're using afterbegin or else you can do it like others gave you examples.
Sorry can't comment not enough reputation and recently joined
I would like to wrap the live content of a DOM element into another, keeping all the structure and all attached event listeners unchanged.
For example, I want this
<div id="original">
Some text <i class="icon></i>
</div>
to become
<div id="original">
<div id="wrapper">
Some text <i class="icon></i>
</div>
</div>
Preferably without jQuery.
If there is nothing else other than ID to distinguish your nodes, and given that #original has multiple child nodes, it would probably be simpler to create a new parent node and insert that:
var original = document.getElementById('original');
var parent = original.parentNode;
var wrapper = document.createElement('DIV');
parent.replaceChild(wrapper, original);
wrapper.appendChild(original);
and then move the IDs to the right place:
wrapper.id = original.id;
original.id = 'wrapper';
noting of course, that the variables original and wrapper now point at the 'wrong' elements.
EDIT oh, you wanted to leave the listeners attached... Technically, they still are, but they're now attached to the inner element, not the outer one.
EDIT 2 revised answer, leaving the event listeners attached to the original element (that's now the outer div):
var original = document.getElementById('original');
var wrapper = document.createElement('DIV');
wrapper.id = 'wrapper';
while (original.firstChild) {
wrapper.appendChild(original.firstChild);
}
original.appendChild(wrapper);
This works simply by successively moving each child node out of the original div into the new parent, and then moving that new parent back where the children were originally.
The disadvantage over the previous version of this answer is that you have to iterate over all of the children individually.
See https://jsfiddle.net/alnitak/d0jss2yu/ for demo
Alternatively, do it this way. It also displays result in the adjacent result div.
<div id="original">
Some text <i class="icon"></i>
</div>
<button onclick="myFunction()">do it</button>
<p type="text" id="result"></p>
<script>
function myFunction() {
var org = document.getElementById("original");
var i = org.innerHTML; //get i tag content
var wrap = document.createElement("div"); //create div
wrap.id="wrapper"; //set wrapper's id
wrap.innerHTML= i //set it to i tag's content
org.innerHTML=""; // clear #orignal first
org.appendChild(wrap); //append #wrapper and it's content
var result = org.outerHTML;
document.getElementById("result").innerText = result;
}
</script>
Updated answer:
This should work better and with less code than my previous answer.
var content = document.getElementById("myList").innerHTML;
document.getElementById("myList").innerHTML = "<div id='wrapper'></div>"
document.getElementById("wrapper").innerHTML = content;
EDIT: This will destroy any event listener attached to the child nodes.
Previous answer:
I don't tried it, but something like this should work:
var wrapper = document.createElement("DIV");
wrapper.id = "wrapper";
var content = document.getElementById("myList").childNodes;
document.getElementById("myList").appendChild(wrapper);
document.getElementById("wrapper").appendChild(content);
Create the wrapper element.
Get myList contents.
Add the wrapper element to myList.
Add myList contents to be child of the wrapper element.
Hello I want to get the nodes of class "ms-qSuggest-listItem" from the id.
<div class="ms-qSuggest-list" id="ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList" style="width: 508px;">
<div class="ms-qSuggest-listItem">Everything</div>
<div class="ms-qSuggest-listItem">Videos</div>
<div class="ms-qSuggest-hListItem">People</div>
<div class="ms-qSuggest-listItem">Conversations</div>
</div>
I tried
var nodes = $get("ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList").class(ms-qSuggest-listItem);
If I wanna get the nodes from its direct class - here its working but I want to get it from the ID.
var nodes = $("div.ms-qSuggest-listItem");
Please help.
Thanks.
All the below selectors will give you the matching nodes.
var nodes = $("#ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList").find('.ms-qSuggest-listItem');
OR
var nodes = $("#ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList .ms-qSuggest-listItem");
OR
var nodes = $(".ms-qSuggest-listItem", "#ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList");
Demo: https://jsfiddle.net/tusharj/fr2d9yv1/
You can use the id in conjunction with the class name within the same selector like this:
var long_id = 'ctl00_ctl38_g....';
var nodes = $('#' + long_id + ' .ms-qSuggest-listItem');
Basically what is happening here is the selector is matching the id and then looking inside it's children for the specified class name.
A more explicit way of writing this would be to use the .find() function on the parent node itself.
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
var long_id = 'ctl00_ctl38_g....';
var parent_node = $('#' + long_id);
var children_nodes = parent_node.find('.ms-qSuggest-listItem');
JSFiddle demo
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);
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.