Hi to everyone, i'm new to javascript and to daniweb, what i want to do is to put all the properties from all the divs of the page, to all their child elements, this way, for example.

<div style="background-color: #000000">
<b>Text</b>
</div>

would change (using javascript)

<div>
<b style="background-color: #000000">Text</b>
</div>

what i've done for now is the following code:

<script languaje=""JavaScript"" type=""text/javascript"">
var x = document.getElementsByTagName('DIV');
for(cont = 0; cont < x.length; cont++)
{
    if(x.item(cont).hasChildNodes())
    {
        document.write('Tiene hijos<br />');
        document.write('-->Hijo(' + x.nodeName + ') ' + cont + ', tiene ' + x.item(cont).length + ' elementos.<br />');
        for(hijo = 0; hijo < x.item(cont).length; hijo++)
        {

        }
    }
    else
    {
        document.write('No tiene hijos');
    }
}
</script>

what i get is the following result:

Tiene hijos
-->Hijo(undefined) 0, tiene undefined elementos.
Tiene hijos
-->Hijo(undefined) 1, tiene undefined elementos.
Tiene hijos
-->Hijo(undefined) 2, tiene undefined elementos.
Tiene hijos
-->Hijo(undefined) 3, tiene undefined elementos.
Tiene hijos
-->Hijo(undefined) 4, tiene undefined elementos.
Tiene hijos
-->Hijo(undefined) 5, tiene undefined elementos.
Tiene hijos
-->Hijo(undefined) 6, tiene undefined elementos.
Tiene hijos
-->Hijo(undefined) 7, tiene undefined elementos.
Tiene hijos
-->Hijo(undefined) 8, tiene undefined elementos.
Tiene hijos
-->Hijo(undefined) 9, tiene undefined elementos.
Tiene hijos
-->Hijo(undefined) 10, tiene undefined elementos.
Tiene hijos
-->Hijo(undefined) 11, tiene undefined elementos.
Tiene hijos
-->Hijo(undefined) 12, tiene undefined elementos.

i thought that when i use the getElementsBy TagName() i would get the DIV elements, with all his childs? but it seems that i only get the element and nothing else.

someone know, how i could do this.

Thanks to everyone!

Eduardo

PS: Sorry for my poor english.

Hi Eduardo,

try to make it in a lowercase format when you specify its tagname: var x = document.getElementsByTagName("div") .

Havnt tried your code yet. Please let me know how it worked..

Eduardo,

With respect to Essential who has already started to answer your question, I wonder if a recursive solution would do the job.

Recursion is where a function includes call(s) to itself. This allows a tree structure (such as a DOM) to be interrogated to any number of levels deep, as opposed to an iterative solution which would require hard-coding a finite number of levels. From your own code, I think you had just realised the limitations of iteration.

Here's a whole html page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Airshow :: Untitled</title>
<style type="text/css">
#DOMList {
	padding : 5px;
	border : 1px solid #006699;
	font-size:9pt;
}
#DOMList p {
	margin : 0;
}
#DOMList p.indent {
	margin-left : 20px;
}
#DOMList h2 {
	margin : 0;
}
#DOMList div {
	margin : 0 0 0 4px;
	padding : 0 0 0 15px;
	border-left : 1px solid #999999;
}
</style>

<script>
function listElements(element, container, seq) {
	seq = (!seq) ? 0 : seq;
	var i, p, p2;
	var fr = document.createDocumentFragment();
	var p = document.createElement('p');
	p.innerHTML = "<b>" + (seq+1) + ". &lt;" + element.nodeName + "&gt;</b>";
	fr.appendChild(p);
	var nextContainer = document.createElement('div');
	var e = element.childNodes;
	if(e && e.length) {
		nextContainer.innerHTML = "<p>Element tiene " + e.length + " hijos.</p>";
		for(i=0; i<e.length; i++) {
			listElements(e[i], nextContainer, i);//NOTE: This is a recursive call
		}
		fr.appendChild(nextContainer);
	}
	else if (element.nodeType == 1) {
		nextContainer.innerHTML = "<p>Element no tiene hijos.</p>";
		fr.appendChild(nextContainer);
	}
	container.appendChild(fr);
}
onload = function(){
	listElements( document.body, document.getElementById("DOMList") );
}
</script>
</head>

<body>

<h1>Heading 1</h1>
<p>text 1</p>
<div>text 2
<p>text 3</p>
</div>
<div></div>

<div id="DOMList"></div>

</body>
</html>

You will see differences in Firefox versus IE. The former treats white space between elements as a text element, while the latter does not.

Airshow

Hi,

here's your requested code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<title>www.daniweb.com</title>
</head>
<body>
<div id="div-0" style="background-color : #000000; color : #FFFFFF">
<b>Div1 Text #1</b><br>
<b>Div1 Text #2</b></div>

<div id="div-1" style="background-color : #EE0000; color : #FFFFFF">
<b>Div2 Text #1</b><br>
<b>Div2 Text #2</b></div>
<script type="text/javascript">
<!--
var d = document;
( function( ) {
   var x = null;
   if ( x = d.getElementsByTagName("div")) {
   var eLen = x.length;
      for ( var i = 0; i < eLen; i++ ) {
      var div = x[ i ];     
         if ( div.hasChildNodes() ) {
         var childs = div.childNodes;
         var cLen = childs.length;
            for ( var j = 0; j < cLen; j += 1 ) {
               if ( childs[ j ] && childs[ j ].nodeName.toLowerCase() === "b" ) {   
            var attribute = div.getAttribute( "style" );
            var setAttr = d.createAttribute( "style" );
            setAttr.nodeValue = attribute;
            childs[ j ].setAttributeNode( setAttr );
               }
            } div.removeAttribute( "style" );
         }
      } return; 
   } alert( "Failed to execute the script, please update your browser" );
   return false;
} )( )

// -->
</script>
</body>
</html>

Hi Airshow,
sorry if I came late and didnt noticed that you had your post.

Have a good day ahead...

Ess, we posted almost simultaneously. With more practise we can be in the Olympics doing "synchronised posting" :icon_lol:

Airshow

Thanks to everyone for the comments and useful code!

I will see how it works, and put it in my script.

Thanks again!

Hi to everyone:

<script type=""text/javascript"">
<!--
var d = document;
( function( ) {
	var x = null;
	if ( x = d.getElementsByTagName(""div"")) {
		var eLen = x.length;
        document.write('Num de Elementos: ' + eLen + '<br />');
		for ( var i = 0; i < eLen; i++ ) {
            document.write('-->Bucle I = ' + i + ' de ' + (eLen-1));
			var div = x[ i ];
			document.write(', x[i] = ' + x[i] + ', Tipo: '+x[i].nodeName+'<br />');
            if ( div.hasChildNodes() ) {
                document.write('----> Tiene Hijos');
				var childs = div.childNodes;
				// READ THE COLOR AND SAVE IT TO A VARIABLE
                var bgColor = div.style.backgroundColor;
                document.write(' color: (' + bgColor + ') ');
				var cLen = childs.length;
				document.write('Num de Elementos: ' + (cLen-1) + '<br />');
                for ( var j = 0; j < cLen; j += 1 ) {
                    document.write('------>Dentro del FOR '+j+' de '+cLen+' Elementos '+ childs[j].nodeName +'<br />');
					COPY TO CHILD BACKGROUND COLOR STYLE
				} 
                //DELETE DIV BACKGROUND COLOR ATRIBUTTE
			}
		} 
        return;
	} 
    alert( ""Failed to execute the script, please update your browser"" );
return false;
} )( )
// -->
</script>

I've just changed a little bit of code, but i try to add the missing parts, but the code does nothing, i'm using firefox with firebug, and i can see that the style properties are in the dom, but they all appera empty, the properties in the HTML, not in the <style> appera to be a new node. see picture

http://www.subirimagenes.com/otros-untitled-3075072.html

I hope you can help me, thanks to everyone!

Eduardo,

Maybe I misunderstood your requirement but if you decide to try my code, then please use the version below, which is more compact, and lists only <div>s at the top level (then all child elements at nested levels).

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Airshow :: Untitled</title>
<style type="text/css">
#DOMList {
	padding : 5px;
	border : 1px solid #006699;
	font-size:9pt;
}
#DOMList p {
	margin : 0;
}
#DOMList div {
	margin : 0 0 0 4px;
	padding : 0 0 0 15px;
	border-left : 1px solid #999999;
}
</style>
<script>
function listElements(name, e, seq) {
	seq = (!seq) ? 0 : seq;
	var i, d = document, fr = d.createDocumentFragment(), p = d.createElement('p');
	p.innerHTML = "<b>" + (seq+1) + ". " + name + "</b>&nbsp;Tiene " + e.length + " hijos.";
	fr.appendChild(p);
	if(e.length) {
		var c = d.createElement('div');
		for(i=0; i<e.length; i++) {
			c.appendChild(listElements('&lt;'+e[i].nodeName+'&gt;', e[i].childNodes, i));//NOTE: This is a recursive call
		}
		fr.appendChild(c);
	}
	return(fr);
}

onload = function(){
	var c = document.createElement('div');
	c.setAttribute('id', 'DOMList')
	c.appendChild(listElements( 'Base', document.getElementsByTagName('div') ));
	document.body.appendChild(c);
}
</script>
</head>

<body>

<h1>Heading 1</h1>
<p>text 1</p>
<div>text 2
<p>text 3</p>
</div>
<div></div>

</body>
</html>

As I say, it may not be what you are seeking but hope it might be useful anyway as a lesson in recursion.

Airshow

Airshow, thank you very much for your example code, i will check it later at night, my problem is that i don't know exactly how work the dom tree in javascript, but i think i'm getting an small idea of how everything works.

Thanks again! i will keep you posted about how everything goes.

Hi to everyone, me again!

it seems i can only acces those properties that are declared in the style="" property of the element.

For example if i have this HTML:

<head>
<style>
.prop1 {
background-color : #000000; color : #FFFFFF
}

.prop2 {
background-color : #EE0000; color : #FFFFFF
}
</style>
</head>
<body>
<div id="div-0" class="prop1">
<b>Div1 Text #1</b><br>
<b>Div1 Text #2</b></div>

<div id="div-1" class="prop2">
<b>Div2 Text #1</b><br>
<b>Div2 Text #2</b></div>

I can't access those properties, but if that html is like this, i can:

<head>
<title>www.daniweb.com</title>
</head>
<body>
<div id="div-0" style="background-color : #000000; color : #FFFFFF">
<b>Div1 Text #1</b><br>
<b>Div1 Text #2</b></div>

<div id="div-1" style="background-color : #EE0000; color : #FFFFFF">
<b>Div2 Text #1</b><br>
<b>Div2 Text #2</b></div>

(i've used the sample code, from a reply above, thanks)

Someone know, how i can access the properties, defined in the header <style>.

PS: You can see the same behaviour in firebug, you can only see those properties that are declared in the element.

Thanks!

Eduardo,

I understand better what you are trying to achieve and think you need to investigate what is called the "computed" style values, ie. those that result from the implementation of the entire cascade.

Unless specifically set, values default to either 'inherit' (the value is inherited from their parent or parent.parent etc.) or 'auto' (the value is preset for the type of element).

I know enough to say that this is quite a tricky topic, as computed values are accessed differently in different browsers. I think you will need to research "css computed values".

Sorry I can't give you more information but hope this little helps.

Airshow

Airshow, thanks for the tip, i will check that topic!

If i have any news or a working code, i will post everything here...

Thanks again!

Hi to everyone.
I searched google, and i found the following example:

http://www.java2s.com/Tutorial/JavaScript/0440__Style/GetComputedStyle.htm

I try to access the .style property from e or get the computedstyle property from the e element in document, but i get "undefined" everythime.

PS: I've addes a new parameter to the function, i wan't to transfer that property to all the children if it's a div.

Thanks!

<script type="text/javascript">
<!--
function listElements(name, e, seq, bgColor) {
	seq = (!seq) ? 0 : seq;
	var i, d = document, fr = d.createDocumentFragment(), p = d.createElement('p');
    if(e.nodeName = 'div')
    {
        //Get Computed backgroundColor;
        //document.defaultView.getComputedStyle(e, null).backgroundColor
        e.style.backgroundColor = "transparent"; // Delete Style Color
    }
    else
    {
        e.style.bacgroundColor = bgColor;
    }
  
	p.innerHTML = "<b>" + (seq+1) + ". " + name + "</b>&nbsp;Tiene " + e.length + " hijos. Color de fondo ";
	fr.appendChild(p);
	if(e.length) {
		var c = d.createElement('div');
		for(i=0; i<e.length; i++) {
			c.appendChild(listElements('&lt;'+e[i].nodeName+'&gt;', e[i].childNodes, i, bgColor));
		}
		fr.appendChild(c);
	}
	return(fr);
}

onload = function(){
	var c = document.createElement('div');
	c.setAttribute('id', 'DOMList')
	c.appendChild(listElements( 'Base', document.getElementsByTagName('div') ));
	document.body.appendChild(c);
}
// -->
</script>

Thanks, to everyone!

i've found this, i hope it will help:

<head>
<style type="text/css">
#test{
width: 100px;
height: 80px;
background-color: yellow;
}
</style>
</head>

<body>
<div id="test">This is some text</div>

<script type="text/javascript">

function getStyle(el, cssprop){
 if (el.currentStyle) //IE
  return el.currentStyle[cssprop]
 else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox
  return document.defaultView.getComputedStyle(el, "")[cssprop]
 else //try and get inline style
  return el.style[cssprop]
}

var mydiv=document.getElementById("test")

alert(getStyle(mydiv, 'width')) //alerts 100px
alert(getStyle(mydiv, 'backgroundColor')) //alerts yellow

</script>
</body>

This is the code i have right now, the variable elem get a null value, why?

<script type=""text/javascript"">
<!--
function listElements(name, e, seq, bgColor, nombre) {
	seq = (!seq) ? 0 : seq;
	var i, d = document, fr = d.createDocumentFragment(), p = d.createElement('p');
    var nombre = nombre + seq;
    e.id = nombre;
    if(e.nodeName = 'div') {
        var elem = document.getElementById(e.id);  
        bgColor = document.defaultView.getComputedStyle(elem,null).getPropertyValue('background-color'); 
    } else {
        e.style.bacgroundColor = bgColor;
    }
  
	p.innerHTML = ""<b>"" + (seq+1) + "". "" + name + ""</b>&nbsp;Tiene "" + e.length + "" hijos. Color de fondo "" + bgColor + "" id = "" + e.id;
	fr.appendChild(p);
	if(e.length) {
		var c = d.createElement('div');
		for(i=0; i<e.length; i++) {
			c.appendChild(listElements('&lt;'+e[i].nodeName+'&gt;', e[i].childNodes, i, bgColor, nombre));
		}
		fr.appendChild(c);
	}
	return(fr);
}

onload = function(){
	var c = document.createElement('div');
    var nombre = ""ofix_"", bgColor = """";
	c.setAttribute('id', 'DOMList')
	c.appendChild(listElements( 'Base', document.getElementsByTagName('div'),0,bgColor, nombre));
	document.body.appendChild(c);
}
// -->
</script>

update:

it still doesn't work:

<script type=""text/javascript"">
<!--
function getBgColor(element) 
{
  if (element.currentStyle)
    return element.currentStyle.backgroundColor;
  if (window.getComputedStyle)
  {
    var elementStyle=window.getComputedStyle(element,"""");
    if (elementStyle)
      return elementStyle.getPropertyValue('background-color');
  }
  // Return 0 if both methods failed.  
  return 0;
}

function listElements(name, e, seq, bgColor) {
	seq = (!seq) ? 0 : seq;
	var i, d = document, fr = d.createDocumentFragment(), p = d.createElement('p');
    if(e.nodeName = 'div') {
        bgColor = getBgColor(e);
        e.style.backgroundColor = 'trasparent';
    } else {
        e.style.backgroundColor = bgColor;
    }
  
	p.innerHTML = ""<b>"" + (seq+1) + "". "" + name + ""</b>&nbsp;Tiene "" + e.length + "" hijos. Color de fondo "" + bgColor + "" id = "" + e.id;
	fr.appendChild(p);
	if(e.length) {
		var c = d.createElement('div');
		for(i=0; i<e.length; i++) {
			c.appendChild(listElements('&lt;'+e[i].nodeName+'&gt;', e[i].childNodes, i, bgColor, nombre));
		}
		fr.appendChild(c);
	}
	return(fr);
}

onload = function(){
	var c = document.createElement('div');
    var bgColor = """";
	c.setAttribute('id', 'DOMList')
	c.appendChild(listElements( 'Base', document.getElementsByTagName('div'),0,bgColor));
	document.body.appendChild(c);
}
// -->
</script>

Edouardo,

The function getStyle(el, cssprop){...} seems to work fine - nice find. I have rolled it into my recursive code here and I'm think you can work with it for what you want.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Airshow :: Untitled</title>
<style type="text/css">
h1#xx {
   padding : 20px;
}
#DOMList {
	padding : 5px;
	border : 1px solid #006699;
	font-size:9pt;
}
#DOMList p {
	margin : 0;
}
#DOMList div {
	margin : 0 0 0 4px;
	padding : 0 0 0 15px;
	border-left : 1px solid #999999;
}
#DOMList ul {
	margin : 0 0 0 15px;
	padding : 0;
}
</style>

<script>
function listElements(name, e, prList, seq) {
	seq = (!seq) ? 0 : seq;
	var i, d = document, fr = d.createDocumentFragment(), p = d.createElement('p');
	prList = (!prList) ? d.createElement('ul') : prList;
	p.innerHTML = "<b>" + (seq+1) + ". " + name + "</b>&nbsp;Tiene " + e.length + " hijos.";
	fr.appendChild(p);
	fr.appendChild(prList);
	if(e.length) {
		var c = d.createElement('div');
		for(i=0; i<e.length; i++) {
			var propsList = listProps(e[i]);
			c.appendChild(listElements('&lt;'+e[i].nodeName+'&gt;', e[i].childNodes, propsList, i));//NOTE: This is a recursive call
		}
		fr.appendChild(c);
	}
	return(fr);
}

function listProps(el){
	var d = document;
	var ul = d.createElement('ul');
	var i=0;
	for (prop in el.style){
		var li = d.createElement('li');
		var val = el.style[prop] || getStyle(el, prop);
		li.appendChild(d.createTextNode(prop + ' = ' +  val));
		ul.appendChild(li);
		i++;
	}
	var li = d.createElement('li');
	var txt = d.createTextNode(i);
	li.appendChild(txt);
	ul.appendChild(li);
	return ul;
}

function getStyle(el, cssprop){
	if(el.currentStyle) { return el.currentStyle[cssprop]; }//IE
	else if(document.defaultView && document.defaultView.getComputedStyle) { return document.defaultView.getComputedStyle(el, "")[cssprop]; }//Firefox
	else { return el.style[cssprop]; }//try to get inline style
}

onload = function(){
	var c = document.createElement('div');
	c.setAttribute('id', 'DOMList')
//	c.appendChild(listElements( 'Base', document.getElementsByTagName('div') ));
	c.appendChild(listElements( 'Base', document.body.childNodes ));
	document.body.appendChild(c);
}
</script>
</head>

<body>

<h1 style="padding:20px;">Heading 1</h1>
<p>text 1</p>
<div>text 2
	<p>text 3</p>
</div>
<div></div>

</body>
</html>

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.