How to make all child elements red - javascript

This is the html code:
<div id="sm-responsive-one">
<p> Step one </p>
<div style="">1</div>
<div style="">2</div>
<div style="">3</div>
<div style="">4</div>
</div>
<div id="sm-responsive-two">
<p> Step two </p>
<div style="">5</div>
<div style="">6</div>
<div style="">7</div>
<div style="">8</div>
</div>
Problem: I want to make 1,2,3 and 4 (child element of sm-responsive-one read color using JavaScript and without using any loop. Is it possible?
This is the code I am trying:
<script>
document.getElementById("sm-responsive-one").getElementsByTagName("div").style.color="red";
//document.getElementById("sm-responsive-one").getElementsByTagName("div")[2].style.color="red";
</script>

You need to use a loop, as getElements* return pseudo-arrays.
If you don't want to use the literal loop syntax, you could apply Array.prototype.forEach, but that's still a loop internally.
var children = document.getElementById("sm-responsive-one").getElementsByTagName("div");
Array.prototype.forEach.call(children, function (it) {
it.style.color="red";
});

First add this CSS rule:
.red-children div {color: red}
Then the javascript is:
document.getElementById('sm-responsive-one').className = "red-children"

getElementsByTagName returns HTML elements collection, so you need to iterate over them:
var elements = document.getElementById("sm-responsive-one").getElementsByTagName("div");
for( var i = 0, len = elements.length; i < len; i++ ) {
elements[ i ].style.color = 'red';
}

Try this:
$("#sm-responsive-one > div").css("color","red");
Check this fiddle:
http://jsfiddle.net/v6xxws1z/

Related

Counting variable name, which will get appended

I have some trouble with my web project.
I'm looking for a solution how I can count my variable upwards in a loop.
So that the name of the variable will go like this: panel1, panel2, panel3...
Thats my code
var panel = []
for(i=1; i<3; i++){
var $div = $('<div class="panel3" id="panel3">Box2 - 20</div>');
$('.panel[i]').append($div);
}
so the "panel[i]" at the bottom should get a higher number for every loop.
I was looking a long time for a solution, but nothing worked.
The idea behind my code is to fill all those empty boxes with a div.
Some HTML
<div class="panel-body">
<!-- Reihe 1 -->
<div class="row">
<div class="col-md-2">
<div class="panel1">
</div>
</div>
<div class="col-md-2">
<div class="panel2">
</div>
</div>
And so on...
Thanks for the help
If your panel name will be panel1, panel2, panel3, so on then you cannot do with this $('.panel[i]'). Instead of that do something like,
for(i=1; i<3; i++){
var div = $('<div class="panel3">Box2 - 20</div>');
var panelClass = '.panel'+i;
$(panelClass).append(div);
}
Hope it helps.
All you need to do is String concatenation with the value of i
var $div = $('<div class="panel3" id="panel'+i+'">Box2 - 20</div>');
And also in the below you doesn't need an array. Just use the parent container identity
$(parentSelector).append($div);
In case if you need all the html in an array
panel[i] = $div;

How to split the text retrieved from `div` elements

I have this HTML:
<div class="chip">java<span class="material-icons close">×</span></div>
<div class="chip">spring<span class="material-icons close">×</span></div>
<div class="chip">python<span class="material-icons close">×</span></div>
With the following script I try to retrieve the texts without the x. I get the values of the div elements using their class name, but when passed to split it, the same string returns without any split:
var skills = $('.chip').text();
var arr = skills.split('x');
for(var i=0;i<arr.length;i++){
alert(arr[i]);
}
For example:
var skills = 'javaxspringxpython';
The output remains the same. I know this is because of the .text() method, but not sure how to solve this. I tried using .val(), but that didn't work.
How can I resolve this?
Your HTML has already three separate elements.
Instead of splitting the combined text, you could get the individual contents of the tags, and kick out any other tags from that content (the span elements in your case). Then you will have three matching text nodes, which you then need to map to array items:
var skills = $('.chip').contents().filter(function() {
return this.nodeType === 3; // only immediate text in div, not in span
}).map(function() {
return $(this).text();
}).get();
console.log(skills);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="chip">java<span class="material-icons close">×</span></div>
<div class="chip">spring<span class="material-icons close">×</span></div>
<div class="chip">python<span class="material-icons close">×</span></div>
Its Work For Me..
$(document).ready(function() {
var skills = $('.chip').text();
var arr = skills.split('x');
for(var i=0;i<arr.length;i++){
// alert(arr[i]);
console.log(arr[i]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='chip'>javaxspringxpython</div>
Hope Its Work !!!
Happy Coding !!

change label foreach element in html using javascript

I am using both html and velocity and came up with this code. The names and images are stored in an array and this is the code I used to display each of the contents of this array to the page.
#foreach($starter in $starter)
<div class="product">
<div class="color"><img src= "$starter.img" width="100" height="100"></div>
<span class="product-name">$starter.name</span>
<div class="compare-wrap">
<input type="checkbox" id="">
<label id="view">Compare</label>
</div>
</div>
#end
I wanted the label to change from "Compare" to "View Compare" while at the same time storing its id in the array upon checking their correspondng check box. I eventually came up with this code:
var checkedArray = [];
$(":checkbox").change(function(){
if((this).checked){
checkedArray.push(this.id);
document.getElementById('view').innerHTML = "<a href='/compare'>View Compare</a>";
}
else{
checkedArray.splice(checkedArray.indexOf(this.id), 1);
document.getElementById('view').innerHTML = 'Compare';
}
var str = checkedArray.join(', ');
alert(str);
});
but it seems it is only applicable to the first content of the array. Any idea how I can use a foreach code at this point?
document.getElementById() only supports one name at a time and only returns a single node not an array of nodes. You should use a class:
var views = document.getElementsByClassName('view');
var i = views.length;
while(i--) {
views[i].innerHTML = "Compare";
}
HTML
<label class="view">Compare</label>
Element ID must be unique.
Hope it helps.

document.getElementById like function for a particular div

document.getElementById will search th whole document and return the result but here i want the same function for a particular div as i want to search the specific div for an id and based on that i want to execute
here is my code
if(document.getElementById('myId') ) // but it return the result from whole div
{
// Do something
}
else {
// do something else
}
i want something like
if(document.getElementById('myId') in specific div) \\ how to do this
Let say, you are looking for an element(div) with id "childId" within parent div with id "parentId". The Jquery code would be:
$("#parentId").find("#childId")
As a shortform, you can even do
$("#parentId #childId")
Since the above statement will find children in any depth, if you would want a direct child search, (first level child)
$("#parentId > #childId")
Generally ids are unique within the page (or atleast are recommended to be :) ). In such a case, you can directly do
$("#childId")
and still get the child element.
Whichever applies.
You want to search for a specific id for all div
I assume that you know the id you want to search
You can itenerate the document.getElementsByTagName('div') like this
var myID = 4;
for (var i = 0; i < document.getElementsByTagName('div').length; i++){
var res = document.getElementsByTagName('div')[i+1].id;
if(res == myID){
document.body.innerHTML = res;
break;
}
}
And this would be your HTML look like:
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
See Demo here
Or I further assume that yor HTML code is look something like this:
<div id="myId">
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
</div>
Then you can itenerate the document.getElementById('myId').getElementsByTagName('div') like this:
var myID = 3;
for (var i = 0; i < document.getElementById('myId').getElementsByTagName('div').length; i++){
var res = document.getElementsByTagName('div')[i+1].id;
if(res == myID){
document.body.innerHTML = res;
break;
}
}
And See Another Demo Here
id attributes should be unique, so searching an element with an id within another element it's the same as search for that id directly in the whole DOM.
You can return an element only if it is a child of a particular element by using a querySelector:
document.getElementById('evalBar').querySelector('#button_2');
/* returned value: (html BUTTON)
[object HTMLButtonElement]
*/
You could use the querySelector function. IMPORTANT: check browser compatibility!
https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector
Example:
<div id="foo">
<div id="bar">
this is foo-bar
</div>
</div>
<script>
var bar = document.querySelector("#foo #bar")
alert(bar.innerHTML); // result: alert message "this is foo-bar"
</script>

getting text content of specific element

I'm trying to get element text content only ignoring element's descendants, for instance if you look at this HTML:
<p>hello <h1> World </H1> </p>
for element "P" the right output should be ONLY "hello ".
I have checked the function: "element.textContent" but this returns the textual content of a node and its descendants (in my example it will return "hello world").
Thanks,
Considering this HTML:
<div id="gettext">hello <p> not this </p> world?</div>
do you want to extract "hello" AND "world"? if yes, then:
var div = document.getElementById('gettext'), // get a reference to the element
children = [].slice.call(div.childNodes), // get all the child nodes
// and convert them to a real array
text = children.filter(function(node){
return node.nodeType === 3; // filter-out non-text nodes
})
.map(function( t ){
return t.nodeValue; // convert nodes to strings
});
console.log( text.join('') ); // text is an array of strings.
http://jsfiddle.net/U7dcw/
well behind it is an explanation
$("p").clone() //clone element
.children() //get all child elements
.remove() //remove all child elements
.end() //get back to the parent
.text();
The answer i have is the same provided in couple of other answer. However let me try and offer an explanation.
<p >hello<h1>World</h1> </p>
This line will be rendered as
hello World
If you look at this code it will be as follow
<p>hello</p>
<h1>World</h1>
<p></p>
With the <p> tag you do not necessarily need the closing </p> tag if the paragraph is followed by a element.
Check this article
Now you can select the content of the first p tag simply by using the following code
var p = document.getElementsByTagName('p');
console.log(p[0].textContent);
JS FIDDLE
You can use the childNodes property, i.e.:
var p = document.querySelector('p');
p.childNodes[0]; // => hello
jsFiddle
Change your html to
<p id="id1">hello <h1> World </h1> </p>
Use this script,
alert(document.getElementById("id1").firstChild.nodeValue);
Try to provide id for the element which you want to do some operation with that.
Below is the working example, it show output as "hello" as you expected.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showParagraph()
{
alert(document.getElementById('test').innerHTML);
}
</script>
</head>
<body>
<p id="test">hello <h1> World </H1> </p>
<input type="button" onclick="showParagraph()" value="show paragraph" />
</body>
</html>
Plain texts are considered as nodes named #text. You can use childNodes property of element p and check the nodeName property of each item in it. You can iterate over them and select just #text nodes.
The function below loops over all element in document and prints just #text items
function myFunction()
{
var txt="";
var c=document.body.childNodes;
for (i=0; i<c.length; i++)
{
if(c[i].nodeName == "#text")
txt=txt + c[i].nodeName + "<br>";
};
return txt;
}
EDIT:
As #VisioN said in comments, using nodeType is much more safer (for browser compatibility) and recommended.

Categories

Resources