I'm trying to populate an array with the output of my for loop.
In this case, I'm trying to push every result where indexOf does not return -1 in that showArray.
Here's an example of li I want to push in the array.
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="https://randomuser.me/api/portraits/thumb/women/12.jpg">
<h3>soline leclercq</h3>
<span class="email">soline.leclercq#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 05/12/14</span>
</div>
</li>
Here is the Javascript
var showArray = [];
for (var i = 0; i < eachStudent.length; i++) {
var studentName = document.getElementsByTagName("h3");
var studentInfo = studentName[i].innerText;
var filter = inputString.value.toUpperCase();
if (studentInfo.toUpperCase().indexOf(filter) != -1) {
showArray.push(eachStudent[i]);
}
console.log(showArray);
}
So far, the showArray.push(eachStudent[i]) is not working, it's not printing the items to the array. My goal is to fill and empty that array dynamically as the user types in the search bar.
Related
I get data from a service with Axios. Then I take it from the Reducer on the page. I'm inviting the data I've thrown into Redux in a function. I'm parsing a String HTML code with DangerouslySetInnerHtml. And I want to call the h2 tag in the generated html.
With getElementsByTagName I get data in the form of HTMLCollection. But I can't use HTMLCollection in a forEach loop.
//code in page
<div
className="article-content"
dangerouslySetInnerHTML={{ __html: detail !== undefined && detail.content }}
/>
where the function is loaded
<div>{this._renderSideBar()}</div>
Function
var article = document.getElementsByClassName("article-content");
var h2s = article[0]
.getElementsByClassName("article-detail")[0]
.getElementsByClassName("article-content")[0]
.getElementsByTagName("h2");
console.log(h2s) // HTMLCollection 5 result
for(var i = 0; i < h2s.length; i++;){
// not working
console.log(h2s[i]);
}
I want to set up a loop here but I can't use HTMLCollection as array
I tried your code and it works after slight modification. Check below. It iterates through the HTMLCollection and prints the H2s
var article = document.getElementsByClassName("article-content");
var h2s = article[0]
.getElementsByClassName("article-detail")[0]
.getElementsByClassName("article-content")[0]
.getElementsByTagName("h2");
for(var i = 0; i < h2s.length; i++){
console.log(h2s[i]);
}
<div class="article-content">
<div class="article-detail">
<div class="article-content">
<h2>H2 1</h2>
<h2>H2 2</h2>
<h2>H2 3</h2>
<h2>H2 4</h2>
<h2>H2 5</h2>
</div>
</div>
</div>
convert the nodelist to array with follwing:
var inputList = Array.prototype.slice.call(h2s);
for(var i = 0; i < inputList .length; i++;){
// not working
console.log(h2s[i]);
}
I solved the problem.
In function
var detailText = this.props.state.blog.detail;
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(detailText, "text/html");
var h2s = htmlDoc.getElementsByTagName("h2");
let items = [];
for (var i = 0; i < h2s.length; i++) {
items.push(h2s[i].innerText);
}
return items.map((row, i) => {
return (
<li key={i}>
{row}
</li>
);
});
So below I have the HTML code that is part of my draggable/droppable:
Drag from here:
<ul id="sortable1" class="dropBox connectedSortable">
<li class="ui-state-default">Word 1</li>
<li class="ui-state-default">Word 2</li>
<li class="ui-state-default">Word 3</li>
<li class="ui-state-default">Word 4</li>
</ul>
Drop a word onto each iamge: <br>
<ul class = "row">
<li id="drop1" class="dropZones images"><img src="image1.jpg"></li>
<li id="drop2" class="dropZones images"><img src="image2.jpg"></li>
</ul>
<ul class = "row">
<li id="drop_zone3" class="dropZones images"><img src="image3.jpg"></li>
<li id="drop_zone4" class="dropZones images"><img src="image4.jpg"></li>
</ul>
</div>
I am trying to create this using document.createElement() etc. But am having difficulty doing this efficiently.
The purpose of the rows (in above code) are for formatting (using bootstrap4), since there are 6 pictures total in my array, and I want 2 rows of 3.
Below, I have an array that holds all the images' src's. This array is passed into the function. I'm able to create one row/ul, with all of the li's/images inside. But I want to be able to create what I have above, with as little hard coding as possible and as efficiently as possible.
I have:
function createType3(arr)
{
var count = 0;
var length = arr.length;
var list = document.createElement("ul");
list.classList.add("row");
for (var i = 0; i < length; i++)
{
//create list and associated ids and classes
var listPiece=document.createElement("li");
listPiece.classList.add("dropZones","images","list-inline");
listPiece.setAttribute("id","dropZone");
//create image tags and append
var imageSRC = document.createElement("IMG");
imageSRC.setAttribute("src",arr[i]);
listPiece.appendChild(imageSRC);
list.appendChild(listPiece);
}
return list;
}
I'm having trouble doing this, thank you.
You could create a document fragment and add list elements to it. Create a new list whenever i % 3 is zero. Make that 3 an argument so that you can use the function also for lists of any other number of entries:
function createType(arr, groupSize = 3) {
var lists = document.createDocumentFragment(),
list;
for (var i = 0; i < arr.length; i++) {
if (i % groupSize === 0) {
list = document.createElement("ul");
list.classList.add("row");
lists.appendChild(list);
}
//create list and associated ids and classes
var listPiece = document.createElement("li");
listPiece.classList.add("dropZones","images","list-inline");
listPiece.setAttribute("id","dropZone");
//create image tags and append
var imageSRC = document.createElement("IMG");
imageSRC.setAttribute("src", arr[i]);
listPiece.appendChild(imageSRC);
list.appendChild(listPiece);
}
return lists;
}
You could call it like this:
var frag = createType(["img1.png","img2.png","img3.png","img4.png"], 3);
document.body.appendChild(frag); // add it somewhere in your HTML page
I am currently studying JavaScript and I have the following problem. Is it possible to get only the text from a div which has children inside it? I managed to make it work only for the text which appears before the div's children.
PS: I would like to mention that I am trying to achieve this using only pure JavaScript.
var Class = document.querySelectorAll('div,b');
for (var i=0; i < Class.length; i++){
console.log(Class[i].childNodes[0].nodeValue);
}
<div class="Bio">
My name is <b>John Doe</b> and I am coming from Texas
</div>
<div class="Bio">
My name is <b>Jean Frye</b> and I am coming from Alabama
</div>
It's not very clean way, but try something like this :
//get all div's with Bio css class (You can change it)
var Class = document.querySelectorAll('.Bio');
var sp=document.getElementById('res');
var arr=[]; //I put result into array so You can use it where You need
for (var i=0; i < Class.length; i++) {
for(var x=0;x<Class[i].childNodes.length;x++) {
if(Class[i].childNodes[x].nodeValue==null) {
//get value, innerHTML, from <b>
//res.innerHTML+=Class[i].childNodes[x].innerHTML+'<br>';
arr.push(Class[i].childNodes[x].innerHTML);
} else {
//get div innerHTML (before,after every child node
//res.innerHTML+=Class[i].childNodes[x].nodeValue+'<br>';
arr.push(Class[i].childNodes[x].nodeValue);
}
}
}
//show result into that span
for(var i=0;i<arr.length;i++) {
res.innerHTML+=arr[i]+'<br>';
}
<div class="Bio">
My name is <b>John Doe</b> and I am coming from Texas
</div>
<div class="Bio">
My name is <b>Jean Frye</b> and I am coming from Alabama
</div>
<br><br>
<!-- I use this span to show result -->
<span id="res"></span>
var Class = document.querySelectorAll('div');
for (var i=0; i < Class.length; i++){
var children = [];
var boldText = Class[i].querySelectorAll('b')[0].innerText;
var otherText = Class[i].innerText.split(Class[i].querySelectorAll('b')[0].innerText)
children.push(otherText[0]);
children.push(boldText);
children.push(otherText[1]);
console.log(children);
}
Output :-
["My name is ", "John Doe", " and I am coming from Texas"]
["My name is ", "Jean Frye", " and I am coming from Alabama"]
This might do the trick.
You can use innerText to get only the text of your selected element.
var Class = document.querySelectorAll('div');
for (var i=0; i < Class.length; i++){
console.log(Class[i].innerText);
}
<div class="Bio">
My name is <b>John Doe</b> and I am coming from Texas
</div>
<div class="Bio">
My name is <b>Jean Frye</b> and I am coming from Alabama
</div>
For more information, reference the MDN article on innerText
I am having trouble with my onchange not working and storing numbers in an array via a text box.
What I want the code to do is to get statistics on the numbers inputted into the text box. I do this by having the user input numbers into the text box and hit the Enter key to display those numbers. The numbers should be put into an array before being put into a list to display the inputted numbers. However, I keep getting this error where the onchange is not triggering when hitting the Enter key or clicking off of the text box.
Here is an image of the error I am getting when inspecting the code
With the numbers stored in the array, I want to try to get the Mean of the numbers. But, I keep getting the error "NaN" which makes me think that my numbers are not getting stored into the array properly.
Here is the code:
<html>
<head>
<title>Stats</title>
</head>
<p>Array is called numbers. numbers.sort();</p>
<div id="stats">
<input type ="text" id="value" onchange="list()"> <!-- Getting the Onchange Error here -->
<button id="button1" onclick = "list()">Enter</button>
<ul id="list1">
</ul>
<button id="stat_button" onclick="calculateMean()">Get Statistics</button>
<p id="mean">Mean= </p>
</div>
<script>
function list() {
var liElement = document.createElement("li"); //Creating new list element//
var ulElement = document.getElementById("list1"); //Get the ulElement//
var input = document.getElementById("value").value; //Get the text from the text box//
var numbers = []; //create Array called numbers
numbers.push(input);//adds new items to the array
//for loop//
for(var i=0; i < numbers.length; i++) {
liElement.innerHTML = numbers[0]; //Puts the array into the list for display//
ulElement.appendChild(liElement); //add new li element to ul element//
}
}
function calculateMean() {
var meanTotal = 0;
var meanAverage = 0;
var meanArray = [];
for (var i = 0; i < meanArray.length; i++) {
meanTotal += meanArray[i];
}
meanAverage = (meanTotal / meanArray.length);
document.getElementById("mean").innerHTML = meanAverage;
}
</script>
Try adding it through addEventListener instead of inline like that:
document.getElementById('value').addEventListener('change', function(e){
list()
})
The reason the Mean is always NaN is because your mean array is always an empty array when you start with. I think you were referring to a numbers array here.
You will have to declare the array outside the scope of the 2 functions, since it is the common to both.
And it is always a better idea to decouple Javascript and HTML. Bind your events in JS instead of inline event handlers.
Note: When you read the value from the input, it is a string, so convert it to a number before storing it in the numbers array.
HTML
<p>Array is called numbers. numbers.sort();</p>
<div id="stats">
<input type="text" id="value">
<!-- Getting the Onchange Error here -->
<button id="button1">Enter</button>
<ul id="list1">
</ul>
<button id="stat_button">Get Statistics</button>
<p id="mean">Mean= </p>
</div>
JS
document.getElementById('value').addEventListener('change', list);
document.getElementById('button1').addEventListener('click', list);
document.getElementById('stat_button').addEventListener('click', calculateMean);
var numbers = [];
function list() {
var liElement = document.createElement("li"); //Creating new list element//
var ulElement = document.getElementById("list1"); //Get the ulElement//
var input = document.getElementById("value").value; //Get the text from the text box//
numbers.push(input); //adds new items to the array
//for loop//
for (var i = 0; i < numbers.length; i++) {
liElement.innerHTML = numbers[0]; //Puts the array into the list for display//
ulElement.appendChild(liElement); //add new li element to ul element//
}
}
function calculateMean() {
var meanTotal = 0;
var meanAverage = 0;
for (var i = 0; i < numbers.length; i++) {
meanTotal += numbers[i];
}
meanAverage = (meanTotal / numbers.length);
document.getElementById("mean").innerHTML = meanAverage;
}
jsFiddle
Hello i have cart full with Elements
This Ex of one of them
<div class="item-container cart-item">
<div>
<img border="0" onerror="src='http://www.myengravedjewelry.com/Admin/surfing.jpg'" title="Bloody Mary Style Colour Name Necklace" src="http://www.myengravedjewelry.com/Admin/surfing.jpg" alt="1009">
<div class="item-header">
<div class="item-body">
<ul class="item-ul">
<li>
<li>
<li>
<span class="bold-14">Price:14.9 </span>
</li>
<li>
<span>ShortId:1010 </span>
</li>
<li>
<span>LongId:110-01-073-10 </span>
</li>
<li>
<span class="spanDefCat">DefaultCat:334 </span>
</li>
</ul>
</div>
</div>
<div class="item-footer"></div>
</div>
When i press save i go trow each one of this element and check if DefaultCat==0
var elements = document.getElementsByClassName("cart-item");
and i try to get to this defaulCat like this
for(i=0;i<elements.length;i++){
var elementContent=elements[i].find(".spanDefCat").html();
var vars = elementContent.split(" ");
var obj = {};
vars.forEach(function(v) {
var keyValue = v.split(":");
obj[keyValue[0]] = keyValue[1];
});
DefaultCat = obj["DefaultCat"];
ShortId = elements[i].children[1].alt;//New style to take ShortID
if(DefaultCat==0)setDefaultCatToProductId(parseInt(ShortId));
arrSortedOrder[i]=parseInt(ShortId);
}
Any one know how to get to this value?
p.s
Plz Do NOT give me solution with $(.spanDefCat) because when i find deff=0 i need to take ShordId as Well from this element[i]
Try this:
$(".cart-item").each(function(){
var shortId = $(this).find(".bold-14").parent("li").siblings("li").children("span").html();
var shortItem = shortId.replace(' ','').split(":");
var defaultCat = $(this).find(".spanDefCat").html();
var item = defaultCat.replace(' ','').split(":");
if(item[1]==0){
var id = parseInt(shortItem[1]);
//do something
}else{
var id = parseInt(shortItem[1]);
//do something else
}
console.log(defaultCat);
console.log(shortId);
});
Note: Above code give you the DefaultCat:334 and ShortId:1010 so now you can use both in if else statement.
If the format of DefaultCat:334 is same for all cart item then you can check whether it is 0 or not
JSFIDDLE DEMO
I see JQuery tag so i give you a response with JQuery statements.
$(".cart-item").find(".spanDefCat").each(function(index, domEle){
//get text, delete spaces and split
split_result = $(domEle).text().replace(' ','').split(":");
//get only numeric value as string
defaultCat = split_result[1];
//parse into int
defaultCat = parseInt(defaultCat);
//if your var is equal to 0
if(defaultCat == 0){
/*********************
* Type you code here *
**********************/
}
});