Let's say i create dynamically some divs, each has it's dynamically created id (div0, div1, div2, etc.) and i'd like with a function to pass through currently existent divs and put their innerHTML into an array (one, two, three in this case), how can i achieve this in javascript?
html example:
<div contenteditable="false" id="div0">
one
<span id="one-close">
<i class="material-icons">close</i>
</span>
</div>
<div contenteditable="false" id="div1">
two
<span id="two-close">
<i class="material-icons">close</i>
</span>
</div>
<div contenteditable="false" id="div2">
three
<span id="three-close">
<i class="material-icons">close</i>
</span>
</div>
You could also use spread syntax
const divsContents = [...document.querySelectorAll("div>a")].map(e=>e.innerHTML);
console.log(divsContents);
<div contenteditable="false" id="div0">
one
<span id="one-close">
<i class="material-icons">close</i>
</span>
</div>
<div contenteditable="false" id="div1">
two
<span id="two-close">
<i class="material-icons">close</i>
</span>
</div>
<div contenteditable="false" id="div2">
three
<span id="three-close">
<i class="material-icons">close</i>
</span>
</div>
Using some magic from here, because document.querySelectorAll returns a NodeList and not an array, we can get the div elements into an array and use .map() to return the div content into an array.
var divs = [].slice.call(document.querySelectorAll('div'));
console.log(divs.map(div => div.innerHTML));
<div contenteditable="false" id="div0">
one
<span id="one-close">
<i class="material-icons">close</i>
</span>
</div>
<div contenteditable="false" id="div1">
two
<span id="two-close">
<i class="material-icons">close</i>
</span>
</div>
<div contenteditable="false" id="div2">
three
<span id="three-close">
<i class="material-icons">close</i>
</span>
</div>
Ideally you should be using a selector like #divcontainer > div to fetch all the divs in the container, but if you know all the ID's, you can use a selector such as:
document.querySelectorAll('#div0, #div1, #div2')
you can use jquery or javascript function for get your div:
myArray[0] = document.getElementByID("div0").innerHtml;
myArray[1] = document.getElementByID("div1").innerHtml;
myArray[2] = document.getElementByID("div2").innerHtml;
Give same class to divs and access by $('.class-name') or add a container div and get your div array by $('#divId div').
Use a loop after creating a divs collection using querySelectorAll:
let divs = document.querySelectorAll('div');
let arr = [];
for (let i = 0; i < divs.length; i++) {
arr.push(divs[i].innerHTML);
}
console.log(arr);
<div>hi</div>
<div>hi2</div>
<div>hi3</div>
Here is your solution
var arr = [];
function myFunction() {
var anchors = document.getElementsByTagName("a");
for(var i = 0; i < anchors.length; i++){
arr.push(anchors[i].text);
}
}
console.log(arr);
So many ways of doing this. Yet an other way: using ES6 Array.from
let divsA = Array.from(document.querySelectorAll("[id^='div'] a"));
divsA.map(a => console.log(a.innerHTML));
<div contenteditable="false" id="div0">
one
<span id="one-close">
<i class="material-icons">close</i>
</span>
</div>
<div contenteditable="false" id="div1">
two
<span id="two-close">
<i class="material-icons">close</i>
</span>
</div>
<div contenteditable="false" id="div2">
three
<span id="three-close">
<i class="material-icons">close</i>
</span>
</div>
Related
In jQuery Terminal I want to add an API that will return indices of the selection.
Example HTML I have:
<div class="cmd" style="width: 100%; --cursor-line:1; top: 0px;">
<div class="cmd-wrapper" style="">
<span class="cmd-prompt" style="visibility: visible; margin-left: 0px;">
<span data-text="> ">
<span style="width: 2ch;">> </span>
</span>
</span>
<div role="presentation" aria-hidden="true" class="cmd-end-line">
<span data-text="H">
<span>H</span>
</span>
<span data-text="e">
<span>e</span>
</span>
<span data-text="l">
<span>l</span>
</span>
<span data-text="l">
<span>l</span>
</span>
<span data-text="o">
<span>o</span>
</span>
<span data-text=" ">
<span> </span>
</span>
<span data-text="W">
<span>W</span>
</span>
<span data-text="o">
<span>o</span>
</span>
<span data-text="r">
<span>r</span>
</span>
<span data-text="l">
<span>l</span>
</span>
<span data-text="d">
<span>d</span>
</span>
<span data-text=" ">
<span> </span>
</span>
</div>
<div class="cmd-cursor-line" role="presentation" aria-hidden="true">
<span>
<span data-text="x">
<span>x</span>
</span>
<span data-text="x">
<span>x</span>
</span>
<span data-text="x">
<span>x</span>
</span>
<span data-text="x">
<span>x</span>
</span>
<span data-text="x">
<span>x</span>
</span>
</span>
<span class="cmd-cursor" style="">
<span data-text="" class="end">
<span> <span></span></span>
</span>
</span>
<span></span>
</div>
</div>
<textarea autocapitalize="off" spellcheck="false" tabindex="1" class="cmd-clipboard" data-cmd-prompt="> " style=""></textarea>
</div>
This is copy-paste of the DOM after entering "Hello World\nxxxxx" and formatted and pretty printed using https://jsonformatter.org/html-pretty-print
My question is what should I do to get the selection indices?
For example, I have a command like this:
> He|lo wor|d
I should get [2, 8] and if the selection is outside of the range: example
>|>> Hello| world
where >>> is prompt I should get [0, 5] I don't care about the negative. I should also handle when the whole selection is outside
|>>>| Hello World
it should return [0, 0] or null.
How would to implement something like this? Note: that I only care about window.getSelection API it's 100% support, not need to be silly and support
IE8.
You want something like
var range = window.getSelection().getRangeAt(0);
var start = range.startOffset;
var end = range.endOffset;
Note that this code assumes that range.startContainer === range.endContainer (which it often does). If you want to get the text / the length of the text between the start and the end containers, you need to recursively traverse the DOM between them. There is also an issue where the length of the text in the DOM is not the same as the length of the text in HTML (browsers sometimes add spaces and other HTML elements)
You'd be right if you guessed that I've worked a bunch in Javascript with selections. IMO it's kind of a nightmare. Tim Down has written a very popular package called Rangy which I recommend it a lot. You should check it out and see if it meets the requirements of what you are doing.
I've solved the issue myself:
var selection = window.getSelection();
var start = $(selection.anchorNode);
var end = $(selection.focusNode);
var before = start.closest('.cmd [role="presentation"]').prevUntil('.cmd-prompt');
var count = 0;
if (before.length > 1) {
count = before.find('[data-text]').length;
}
var s = start.closest('.cmd [role="presentation"] [data-text]');
var e = end.closest('.cmd [role="presentation"] [data-text]');
if ((s.length || e.length)) {
start = count + s.index();
end = count + e.index() + 1;
console.log({start, end});
}
Say i have a list of ids [[1,2],[4,5,6]]
I am trying to create a parent element for each set of ids, say a div
currently its:
<span id="data-inject">
<br> <br>
<span id=1>Barack</span>
<br> <br>
<span id=2>Obama</span>
<span id=3>xx</span>
<span>
I would like it to be:
<span id="data-inject">
<br> <br>
<div id=test>
<span id=1>Barack</span>
<br> <br>
<span id=2>Obama</span>
</div>
<span id=3>xx</span>
</span>
is there any way to achieve the same using java script?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="data-inject"><br> <br> <span id="0">xx</span> <span id="1">Barack</span> <span id="2">Obama</span> <span id="3">xx</span> <span id="4">Barack</span> <span id="5">Obama</span> <span id="6">Barack</span> <span id="7">Obama</span><br> <br> <span id="8">sdsds</span> <span id="9">Barack</span> <span id="10">Obama</span></span>
Try this :
$('#data-inject').find('span').slice(0,2).wrapAll('<div id="test"></div>').after(' ');
Here is a Jsfiddle : https://jsfiddle.net/8L1mutxr/
.after(' ')
add spaces after elements. But your HTML is very dirty by the way.
Using jquery you can easily create a new element for each array item and then loop through the inner array to search and append to the newly create item,
the example should be auto explanatory:
var arr = [[1,2],[4,5,6], [7,8,9,10]]
arr.forEach((x, i) => {
// we create a parent div for each item
var parent = $('<div class="parent'+ i + '"></div>')
// we append it
$('#data-inject').append(parent)
// we loop through inner arrays and append them to newly created 'parent'
x.forEach(z => {
parent.append( $('#' + z) )
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="data-inject">
<span id="0">xx</span>
<span id="1">Barack</span>
<span id="2">Obama</span>
<span id="3">xx</span>
<span id="4">Barack</span>
<span id="5">Obama</span>
<span id="6">Barack</span>
<span id="7">Obama</span>
<span id="8">sdsds</span>
<span id="9">Barack</span>
<span id="10">Obama</span>
</span>
There are multiple divs of step_input as class and inside those divs may or may not consists spans with same class. I need to check whether a particular span exist in any of the div with class as step_input. Then change the color of spans with same class which exists in selectable-tags class.I had to use javascript only
Here in the fiddle span1 exists in the step_input class. So its color in selectable-tags needs to be changed.
Here's a fiddle Link
var parentz = document.querySelectorAll('step_input');
for(i=0;i<document.querySelectorAll('.selectable-tags > span').length;i++)
{
tagclassName='ing-tag_'+i;
for(k=0;k<parentz.length;k++)
if ( parentz[k].querySelector("."+tagclassName) !== null) {
document.querySelector('.selectable-tags > tagclassName').style.backgroundColor="#fafafa";
}
}
<div class="selectable-tags" >
<span data-class="label" style="background-color: red;" class="ing-tag_0"> Span1 </span>
<span style="background-color: red;" data-class="label" class="ing-tag_1"> wqq </span>
</div>
<div class="selectable-tags" >
<span style="background-color: red" data-class="label" class="ing-tag_0"> Span1 </span>
<span style="background-color: red;" data-class="label" class="ing-tag_1"> wqq </span>
</div>
<div id="step_input_0" name="step" class="recipe-create-text_box_rectangle stepbox step_input" contenteditable="true"> This does not contains anything
</div>
<div value="" id="step_input_1" name="step" placeholder="Tell us about step 2" class="recipe-create-text_box_rectangle stepbox step_input" contenteditable="true"> <span style="background-color: red;" data-class="label" class="ing-tag_0" contenteditable="false"> Span1 </span>Thw color of span 1 in selectable tags needs to change </div>
Edit: When a span with is detected in the step_input. Its corresponding one in .selectable_tags class 's color changes. Like here Span1 with class 'ing-tag_1' is in step_input class. Now the color of Span1 in the div with class selectable_tags 's color needs to be change. Please suggest a better way to do this if there's one.
You need to change color each selectable tag one by by one. The following would check and color the tag which are present in the step_input
var parentz = document.querySelectorAll('.step_input');
console.log(parentz);
for(i=0;i<document.querySelectorAll('.selectable-tags > span').length;i++){console.log(document.querySelectorAll('.selectable-tags > span'));
tagclassName='ing-tag_'+i;
for(k=0;k<parentz.length;k++){
if ( parentz[k].querySelector("."+tagclassName) !== null) {
colorthem= document.querySelectorAll('.selectable-tags > .'+tagclassName) ;console.log(colorthem);
for(l=0;l<colorthem.length;l++)
{console.log(colorthem[l]);
colorthem[l].style.backgroundColor="red";
} }
}}
<div class="selectable-tags" >
<span data-class="label" style="background-color: red;" class="ing-tag_0"> Span1 </span>
<span style="background-color: red;" data-class="label" class="ing-tag_1"> wqq </span>
</div>
<div class="selectable-tags" >
<span style="background-color: red" data-class="label" class="ing-tag_0"> Span1 </span>
<span style="background-color: red;" data-class="label" class="ing-tag_1"> wqq </span>
</div>
<div id="step_input_0" name="step" class="recipe-create-text_box_rectangle stepbox step_input" contenteditable="true"> This does not contains anything
</div>
<div value="" id="step_input_1" name="step" placeholder="Tell us about step 2" class="recipe-create-text_box_rectangle stepbox step_input" contenteditable="true"> <span style="background-color: red;" data-class="label" class="ing-tag_0" contenteditable="false"> Span1 </span>Thw color of span 1 in selectable tags needs to change </div>
Is it this what you need?
var parentz = document.querySelectorAll('.step_input');
var selectable = document.querySelectorAll('.selectable-tags');
for(j=0; j < selectable.length; j++){
var current = selectable[j];
var spans = current.querySelectorAll('.selectable-tags > span');
for(i=0; i < spans.length; i++){
tagclassName='ing-tag_'+i;
for(k=0; k < parentz.length; k++){
if (parentz[k].querySelector("."+tagclassName)) {
selectable[j].querySelector('.' +tagclassName).style.backgroundColor="#fafafa";
}
}
}
}
<div class="selectable-tags" >
<span data-class="label 11" style="background-color: red;" class="ing-tag_0"> Span1 </span>
<span style="background-color: red;" data-class="label" class="ing-tag_1"> wqq </span>
</div>
<div class="selectable-tags" >
<span style="background-color: red" data-class="label" class="ing-tag_0"> Span1 </span>
<span style="background-color: red;" data-class="label" class="ing-tag_1"> wqq </span>
</div>
<div id="step_input_0" name="step" class="recipe-create-text_box_rectangle stepbox step_input" contenteditable="true"> This does not contains anything
</div>
<div value="" id="step_input_1" name="step" placeholder="Tell us about step 2" class="recipe-create-text_box_rectangle stepbox step_input" contenteditable="true">
<span style="background-color: red;" data-class="label" class="ing-tag_0" contenteditable="false"> Span1 </span>
Thw color of span 1 in selectable tags needs to change
</div>
I did not get what you're asking for, but as far as I can see, the selector .selectable-tags > span should work fine for direct children. Which you did already.
EDIT:
First of all,
var parentz = document.querySelectorAll('step_input');
this line checks for tags with the name step_input which does not exist in your HTML, there are IDs with step_input_0 for that you'll need to prepare an array of ID by running a loop. Otherwise you can use document.getElementsByName("step")
Again,
You just have to traverse the DOM, to access the span inside divs with name name it would look something like:
const divsWithStep = document.getElementsByName("step");
divsWithStep.forEach((div)=>{
div.querySelector('span').style.backgroundColor="#fafafa";
})
Again, I think you should look up on DOM traversing, let me know.
I have this html structure, this is a snippet there is lots more in the same structure.
<button id="showEmpty">Press</button>
<div class="children">
<div class="package">
<span class="name"></span>
<span class="value"></span>
</div>
<div class="package array">
<span class="name"></span>
<span class="value"></span>
</div>
<div class="package">
<span class="name"></span>
<span class="value"></span>
</div>
<div class="package array">
<div class="children">
<div class="package array">
<span class="name"></span>
<span class="value"></span>
</div>
<div class="package">
<span class="name"></span>
<span class="value"></span>
</div>
<div class="package array">
<div class="children">
<div class="package array">
<span class="name"></span>
<span class="value"></span>
</div>
<div class="package array">
<span class="name"></span>
<span class="value"></span>
</div>
<div class="package">
<span class="name"></span>
<span class="value"></span>
</div>
</div>
</div>
</div>
</div>
</div>
I want to find all of the div elements with the class 'array' and then the span elements with the class 'value' within those div that dont have any content.
Those that apply I want to change the class of another span element within the div with the class 'name' to say 'empty'.
I have this code so far, but I'm not sure where to go next.
(function(){
$('#showEmpty').click(function() {
if ($('div.package').each().hasClass('array') && $('span.value').each().text().trim().length()) {
$('span.value').removeClass('name').addClass('empty');
else alert('no arrays found');
}
});
});
EDIT: I would also need to only do this where the array div's don't have children div's
One easy way is(assuming the empty span will be <span></span>, ie there is no blank content in it)
jQuery(function ($) {
$('#showEmpty').click(function () {
$('div.package.array').has('span.value:empty').find('span.name').removeClass('name').addClass('empty');
});
});
Here we finds div with classes package and array which has an empty span with class value, then find the span with class name in those div and remove and add class
If the span.value can have blank values then you can use a filter
jQuery(function ($) {
$('#showEmpty').click(function () {
$('div.package.array').filter(function () {
return $('span.value', this).text().trim().length() > 0;
}).find('span.name').removeClass('name').addClass('empty');
});
});
You can use this function:
$('.array').each(function(){
if ($(this).children('span.value').text() === "")
{
$(this).children('span.name').addClass('empty').removeClass('name');
}
});
Fiddle here
$('div.package.array > span.value').each(function () {
$('span.name').removeClass('name').addClass('empty');
});
This is how I would do it:
$('#showEmpty').click(function () {
$(".array > span.value:empty").siblings(".name").removeClass('name').addClass('empty');
});
Here is the JSFiddle demo
You can inspect-element to see the changes on button click.
You can use a code like this:
$(document).ready(function(){
$('#showEmpty').click(function() {
$('div.package span.value').each(function(){
if ($(this).val().length==0) {
$(this).parent().find('span.name').removeClass('name').addClass('empty');
}
});
});
});
Fiddle here: http://jsfiddle.net/n2o55xve/
Hope it helps.
Hey guys – I have the following HTML:
<div>
<span class="icon">
Technology
</span>
</div>
<div>
<span class="icon">
Design
</span>
</div>
<div>
<span class="icon">
Management
</span>
</div>
I'm looking for a short and sweet jQuery snippet that will detect the value in the link, and add that value as a class name for to the span, resulting in the following:
<div>
<span class="icon Technology">
Technology
</span>
</div>
<div>
<span class="icon Design">
Design
</span>
</div>
<div>
<span class="icon Management">
Management
</span>
</div>
I am using:
var categoryName = $(".icon a", this).html();
$(".icon").addClass(categoryName);
But it is only taking the value of the first link and applying that as the class name for each span.
Thanks for the help as always!
$(".icon").each(function(){
$(this).addClass($(this).find("a").html());
});
JSFiddle
You can also do this with a loop:
var spans = $(".icon");
for(var i = 0; i < spans.length; i++)
{
var cspan = $(spans[i]);
$(cspan).addClass($(cspan).find("a").html());
}
JSFiddle
use .each() to iterate over all span with class icon.:
$('.icon').each(function(){
$(this).addClass($(this).find('a').html())
})
Working Fiddle
You can run this on page load or under some event:
$(".icon").each(function(){
var name = $(this).find("a").text();
$(this).addClass(name);
});
You can use:
1) $.each() to loop through the span with class icon
2) .find() to find the child anchor inside your span
3) .text() to get the text of the found anchor:
$.each($('span.icon'), function(){
$(this).addClass($(this).find('a').text());
});
Fiddle Demo