Question
How do you select text node values identified with a specific attribute (background color #00FF00)?
As I'm new to javascript, I'm not sure how to do the first step:
use the js dom to select the node with 00FF00
split the string with " " as the separator
loop through and add each split[2] with +=
write the sum (240+80+600) to html
Code
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
var data = document.getElementsByTagName('span');
document.write(data);
};
</script>
</head>
<body>
<div class="box">
<span class="highlight">Dave collected 700 items.</span>
</div>
<div class="box">
<span class="highlight" style="background-color:#00FF00;">Bob collected 240 items.</span>
</div>
<div class="box">
<span class="highlight" style="background-color:#00FF00;">Bob collected 80 items.</span>
</div>
<div class="box">
<span class="highlight" style="background-color:#00FF00;">Bob collected 600 items.</span>
</div>
</body>
</html>
var els = document.querySelectorAll('span.highlight');
var len = els.length;
//console.log(len); //returns 4
var total = 0;
for (var i=0; i < len; i++) {
if (els[i].style.backgroundColor.toLowerCase() === 'rgb(0, 255, 0)') {
var txt = els[i].innerHTML;
//split txt into array
split = txt.split(" ");
total += parseInt(split[2]);
}
}
console.log(total);
Unless you are trying to scrape the content of another site and have no control over the HTML structure, I would recommend adding an additionnal class or an attribute to these that would ease the selection of these nodes.
However, you could do it like:
var els = document.querySelectorAll('span.highlight'),
i = 0,
len = els.length;
for (; i < len; i++) {
if (els[i].style.backgroundColor.toLowerCase() === '#00ff00') {
//code
}
}
As previously mentioned, it's probably best to use a class definition. But if you must select by color, the following code should do it for you.
var data = document.getElementsByTagName('span');
var len = data.length;
for(var i = 0; i < len; ++i){
var styles = data[i].getAttribute('style');
if(styles.indexOf('background-color:#00FF00') != -1){
//Do something
}
}
Related
I've got an array in Javascript that I want to print to screen which is: (my function for ro[j] is simplified in this example, but that doesn't matter)
<div class="result2"></div>
<script>
var j;
var ro = [0];
for(j=0; j <= 49; j++){
ro[j] = j;
$('.result2').html(ro[j]);
}
</script>
But this doesn't work as I think it keeps replacing the div with each loop rather than adding to the div. Is there a good way to implement this? I thought you could try something like this:
<div class="result2"></div>
<script>
var j;
var ro = [0];
for(j=0; j <= 49; j++){
ro[j] = j;
if(j==0){
$('.result2').html(ro[j]);
}else{
var res = $('.result2').val();
$('.result2').html(res + ro[j]);
}
}
</script>
but this doesn't work since you can't seem to call the result of the script midway through the script? Or I just made a mistake, I'm not sure. Any help would be great!
edit: forgot a semicolon
A list element (ul or ol) should be used for lists as it's more semantically correct:
<ul id="result2"></ul>
Using es6 syntax you can append elements to that list like this:
const ro = [...Array(49).keys()]; // Just setting up a sample array
for (r of ro) {
let li = document.createElement('li');
li.innerHTML = r;
document.getElementById('result2').appendChild(li);
}
This will place the numbers vertically in the screen.
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="result2"></div>
<script type='text/javascript'>
var ro = [];
for (var j = 0; j <= 49; j++) {
ro.push(j);
$('.result2').append(ro[j] + '<br />');
}
</script>
</body>
</html>
I am trying to append new div elements to existing divs by using document.getElementsByTagName("div"), converting it to an array, then using appendChild on it. However, when I inspect the frame source of this jsfiddle, it doesn't seem to append it to the divs. It is just:
<body>
<div id="1">
<div id="2">
test
</div>
</div>
Instead of the expected result:
<body>
<div id="1">
<div id="2">
test
</div><div></div>
</div><div></div>
https://jsfiddle.net/ng58e87w/
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
allDivs[i].appendChild(newDiv);
console.log(allDivs[i]);
}
I can't comment, but I believe you are just creating empty divs and adding nothing to them. They show up created when you inspect element in the jsfiddle. I also set their text to something and it seemed to work.
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
newDiv.innerHTML = "Hidden Div?";
allDivs[i].appendChild(newDiv);
console.log(allDivs[i]);
}
Use .after() instead of .appendChild().
var words = ['apple','banana','cake'];
console.log(words[0]);
object1 = {
name:'frank',
greet:function(){
alert('hello '+this.name)
}
};
object2 = {
name:'andy'
};
// Note that object2 has no greet method.
// But we may "borrow" from object1:
object1.greet.call(object2);
/*
var divs = [];
var arr = Array.prototype.slice.call( document.getElementsByTagName("div") );
for(var i = 0; i < arr.length; i++) {
//do something to each div like
var div = document.createElement("div");
arr[i].appendChild(div);
}
*/
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
allDivs[i].after(newDiv);
console.log(allDivs[i]);
}
<div id="1">
<div id="2">
test
</div>
</div>
I have been stuck on this silly thing, I can't figure out how to wrap my for loop inside of a div.
for (item = 0; item < event.length; item++) {
var ID = event[item].id;
element.find(".title").after("<span class='id'><img src='/avatar/" +ID+ "'/></span>");
}
I want to achive this:
<div>
<span></span>
<span></span>
<span></span>
</div>
Any Help is much apprciated.
Hope this snippet will be useful
// a variable for the dynamically created span
var spanString = "";
for (item = 0; item < event.length; item++) {
var ID = event[item].id;
// new string will con cat wit the spanString
spanString += ("<span class='id'><img src='/avatar/" + ID + "'/></span>");
}
// append the spanString to the `div.title`
$(".title").append($(spanString))
$(document).ready(function() {
//Assume sample event array
var event = [1, 2, 3];
for (item = 0; item < event.length; item++) {
var ID = event[item];
$("<span class='id'><img src='/avatar/" +ID+ "'/></span<br>").appendTo('#name');
};
});
Considering sample HTML Below
<div id="name">
hello
</div>
This way you can populate content inside the div
I'm trying to get the value of data attributes from multiple div elements. The elements are captured into a variable using
querySelectorAll()
I'm getting an error when I loop through the variable that contains the element and use the getAttribute() Method:
<div id="container">
<div class="box" data-speed="2" id="one"></div>
<div class="box" data-speed="3" id="two"></div>
<div class="box" data-speed="4" id="three"></div>
<div class="box" data-speed="5" id="four"></div>
<div class="box" data-speed="6" id="five"></div>
</div>
js:
(function() {
var boxes = document.getElementsByClassName("box");
for (var i = 0; i < boxes.length; i++) {
var r = Math.floor((Math.random() * 254) + 1);
boxes[i].style.background = "rgba(" + r + "," + i*30 + "," + i*45 + ", 1)";
}
})();
var divArray = [];
var divs = document.querySelectorAll(".box");
for (i = 0; i <= divs.length; i++) {
console.log(divs[i]);
var speed = parseInt(divs[i].getAttribute("data-speed"));
};
Jsfiddle https://jsfiddle.net/kshatriiya/L8xsvzL1/1/
When I
console.log(divs[i])
it shows the element, I don't know why I'm unable to use the attribute method on it.
Any pointer would be really appreciated!
Arrays in javascript are 0 index based
use
for (i = 0; i < divs.length; i++) {
instead of
for (i = 0; i <= divs.length; i++) {
due to this you are getting last divs[i] as undefined and thats why console display that error
updated fiddle : https://jsfiddle.net/n3qhan4e/
It's simple
document.querySelectorAll('.box').forEach(elem => console.log(elem.getAttribute('data-speed')));
I have made a code that needs to make page-breaks after certain number of new lines or words. I have set up an array that tell me where it should cut in my element. As you can see in my jsFiddle you can see a console.log(); that shows I need to cut the text.
I would like to get help on how to create a closing </div> inserted after the specific string from my array(). I would like to have a closing </div> and a creation of a new <div>
More details about the code
// $(this)
$(this) = $('.c_84');
The HTML example
<div class=" onerow counting_1"><div class="newDiv"></div>
<div class="onefield c_6937">
<!-- This is where I want to generate the new divs -->
<table class="textarea" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td class="value"><!-- Content String --></td>
</tr>
</tbody>
</table>
</div>
</div>
Here is my code logic so far.
// The class c_6937 is the class test in my jsFiddle
// I did this just to remove extra html and focus on the problem
// Start
$(this).find('.c_6937').parent().prepend('<div class="newDiv">');
var countReqNumberOfPages = newChunk.length;
for (var key in newChunk) {
// If we find the first chunk, insert </div><div class="newDiv"> after it.
}
// End
$(this).find('.c_6937').parent().append('</div>');
Could it be possible to run a str_replace() function inside my array() and replace the current string with the exact same string plus the closing divs?
EDIT 1 : I added extra comments in the code for a better understanding of the problem and added a possible solution.
I'm not sure whether you are after something like this
<script type="text/javascript">
var wordsPerLine = 15;
var minWordsPerLine = 5;
var linesPerPage = 30;
var linesToStopAfter = [];
function checkForDot(pos,masterArray){
if(pos < 0){
return false;
}
var line = masterArray[pos];
if(line.indexOf('.') !== -1){
return line;
}
else{
return checkForDot(pos-1,masterArray);
}
}
function chunk(lines) {
var masterLines = [];
for (i = 0; i < lines.length; i++) {
var sentence = [];
var wordsList = lines[i].split(" ");
var wordCount = 0;
for (j = 0; j < wordsList.length; j++) {
if(wordCount >= wordsPerLine){
wordCount = 0;
masterLines.push(sentence.join(" "));
sentence = [];
sentence.push(wordsList[j]);
}
else{
sentence.push(wordsList[j]);
}
wordCount++;
}
masterLines.push(sentence.join(" "));
}
return masterLines
}
$(document).ready(function()
{
var html = $("#test").html();
$("#test").html('<div class="newDiv">'+html+'</div>');
var lines = chunk($("#test").text().split("\n"));
var count = 0;
for (k = 0; k < lines.length; k++) {
count++;
if(count >= linesPerPage){
count = 0;
linesToStopAfter.push(checkForDot(k,lines));
}
}
for(j=0; j<linesToStopAfter.length;j++)
{
toreplace = $("#test").html().replace(linesToStopAfter[j], linesToStopAfter[j]+"</div><div class='newDiv'>");
$("#test").html(toreplace)
}
cleanedhtml = $("#test").html().replace(/<\s*div[^>]*><\s*\/\s*div>/g,"");
$("#test").html(cleanedhtml)
});
</script>