Jump to content

How to access an element in the DOM ?


brucemand

Recommended Posts

<script>function checkme(){	// var chk=document.getElementById('pics');	var chk=document.getElementById('pic1');	alert(chk.tagName);}</script></head><body><div id="pics" onClick="checkme()" ><img id="pic1" src="a.jpg" /><img id="pic2" src="b.jpg" /></div>

i originally tried to access the <img> via chk.firstChild, but that 'alert'-ed "undefined" (tagName, innerHTML & value)i then created individual Id-s but now it's an error.EDIT: sorry, found the error, but would still like to access the <img>-s per <div> rather than having to index all <img>-show should i be doing this ?------------2nd EDIT: have changed the subject for another similar scenario. not sure if it's better to start a new thread or append this one since it's a similar situation of accessing nested elements.

Link to comment
Share on other sites

i then created individual Id-s but now it's an error.
What's the error? It shouldn't be an error.If you want to access them without having to use unique ids for each one you can do that in several ways. The easiest is probably getElementsByTagName.You already have the container object selected:var picsContainer = document.getElementById('pics');Now you just need to get all the image tags in that container:var imgs = picsContainer.getElementsByTagName('img');Now you have an array of images you can loop through and do whatever you need to do:
for (var x=0, y=imgs.length; x<y; x++) {   alert(imgs[x].src);}

Link to comment
Share on other sites

What's the error? It shouldn't be an error.If you want to access them without having to use unique ids for each one you can do that in several ways. The easiest is probably getElementsByTagName.//cut//
you are right, i had something other function going on which affected those <img> elements. :) i did try the get by TagNames in the end, but would still prefer to access them by <div>.the full version would look something like;
<div id="pics">  <img id="pic1" src="a.jpg" />  <img id="pic2" src="b.jpg" /></div><div id="photos">  <img id="photo1" src="a.jpg" />  <img id="photo2" src="c.jpg" />  <img id="photo3" src="e.jpg" /></div><div id="sketches">  <img id="sketch1" src="b.jpg" />  <img id="sketch2" src="d.jpg" /></div>

what are those other ways that you mentioned ?also, are the <img>-s not the '.firstChild' of the <div> ?

Link to comment
Share on other sites

i did try the get by TagNames in the end, but would still prefer to access them by <div>.
what do you mean? Isn't that what SM showed you?
Link to comment
Share on other sites

what do you mean? Isn't that what SM showed you?
later, i want to write a function that will perform similar actions to the images.if i get ALL <img>-s i will have to perform a different index check for each set of <img>-s in each <div>.the indices may not be not be known beforehand, and if i could access them by .firstChild, or at least, as an array *within* the <div> it would be better.my question remains, is the <img> in the above example NOT a firstChild of the <div> element ?EDIT:*ARGH*i didn't read SM's post carefully :)
Now you just need to get all the image tags in that container:var imgs = picsContainer.getElementsByTagName('img');
i didn't realise getElementsBy_ was an applicable method downstream !i've only been using it on the 'document' itself all this time !!many *THANKS* then
Link to comment
Share on other sites

In most browsers, the .firstChild of an element could be a text node containing the line breaks and tabs that format your document. You should never count on it being an HTML element.In Shadow's example, imgs[0] would refer to the first child that is an image.

Link to comment
Share on other sites

You can access the elements within the div like this: document.getElementById("photos").getElementsByTagName("img")This returns a nodelist of all the image elements that are descendents of the "photos" element.

Link to comment
Share on other sites

In most browsers, the .firstChild of an element could be a text node containing the line breaks and tabs that format your document. You should never count on it being an HTML element.In Shadow's example, imgs[0] would refer to the first child that is an image.
i see.okay thanks for that, .firstChild is probably not a good property to use unless the DOM.tree is strictly set up.
Link to comment
Share on other sites

You can access the elements within the div like this: document.getElementById("photos").getElementsByTagName("img")This returns a nodelist of all the image elements that are descendents of the "photos" element.
okay, cool - i like that oneshot process of "property of property" !otherwise i would've relayed it via 'var's !
Link to comment
Share on other sites

  • 2 weeks later...
You can access the elements within the div like this: document.getElementById("photos").getElementsByTagName("img")This returns a nodelist of all the image elements that are descendents of the "photos" element.
this does also work if the target element is an extra container 'deeper' ?like so;
<div id="thelist"><td><input type="text" size="2" readonly="readonly" value="'somesuch1" /></td><td><input type="text" size="3" readonly="readonly" value="somesuch2" /></td><td><input type="text" size="4" readonly="readonly" value="somesuch3" /></td></div>

would document.getElementById("thelist").getElementsByTagName("input")return the <input>s ?or would i have to 'id' the <td> ?

Link to comment
Share on other sites

this does also work if the target element is an extra container 'deeper' ?like so;
<div id="thelist"><td><input type="text" size="2" readonly="readonly" value="'somesuch1" /></td><td><input type="text" size="3" readonly="readonly" value="somesuch2" /></td><td><input type="text" size="4" readonly="readonly" value="somesuch3" /></td></div>

would document.getElementById("thelist").getElementsByTagName("input")return the <input>s ?or would i have to 'id' the <td> ?

getElementsByTagName returns every single descendent no matter how deep it is.
Link to comment
Share on other sites

getElementsByTagName returns every single descendent no matter how deep it is.
ok, thanks - i must be doing something else wrong then.
Link to comment
Share on other sites

Just so you know, that HTML is invalid. You're not allowed to have any content directly inside a tr element. That might be causing issues in the JavaScript.
the <tr> element ?but i think i get your point, that was a sloppy Object definition with <div> & <td>.i eventually dumped the <td>s since they were actually superfluous and it then worked.but even if it was a <tr>, not even CSS style is allowed ?
Link to comment
Share on other sites

ANOTHER SCENARIOmore complex, includes PHP as well;

<script type="text/javascript">function tester() {var a=2;alert(a);}function editer(qnum) {		// careful PHP & JS using SAME var.name without '$' !	var pqid="parq"+qnum;	var parq=document.getElementById(pqid);// still need to explode the array//alert(parq.length) = 'undefined'//OK	alert(parq.innerHTML);	// only the Q itself !	var parli=parq.getElementsByTagName('li');	alert(parli.length);	// this is '0' -> no <li> found ?}</script><?php	$manual = "<p>@What do you think of this ?";	$manual.= "<ul><li>a) Yes</li><li>b) No</li><li>c) Okay</li><li>d) Maybe</li></ul>";	$manual.= "</p>";	$fileread = $manual or die ("Could not read file!");$qnum=1;//	foreach ($fileread as $perPelement) {		$perPelement=explode("@",$fileread);	// only 2 pcs; <p> and the rest	echo '<span onClick="editer('.$qnum.')" style="background:#e3e">EDIT</span>';	echo '<p id="parq'.$qnum.'" style="background:#eee">'.$qnum.') ';	echo $perPelement[1];	$qnum++;//	}?>

is the <li> not an element "get"table by getElementsByTagName('li'); ?

Link to comment
Share on other sites

Your code isn't putting any lists inside and of your <p> elements. But browsers will never put a list inside a <p> element anyways; the list will follow the paragraph.You should put the ID on the <ul> element and not the <p> element.

Link to comment
Share on other sites

the <tr> element ?but i think i get your point, that was a sloppy Object definition with <div> & <td>.i eventually dumped the <td>s since they were actually superfluous and it then worked.but even if it was a <tr>, not even CSS style is allowed ?
I assumed that, since you had <td> tags, this was part of a table which would thus have <tr> tags. But you are also not allowed to use <td> tags outside of <tr> tags, so either way, the code was invalid.You can style <tr> elements, but there are quite a few properties that have no effect.
ANOTHER SCENARIOmore complex, includes PHP as well;....code....is the <li> not an element "get"table by getElementsByTagName('li'); ?
Not really sure I understand the question. Are you asking if you can access the <li> elements using getElementsByTagName? Yes, you can access any element.
Link to comment
Share on other sites

Your code isn't putting any lists inside and of your <p> elements. But browsers will never put a list inside a <p> element anyways; the list will follow the paragraph.You should put the ID on the <ul> element and not the <p> element.
not sure what you mean by that text - "...inside any(?) of your <p>... " ?does this;
	$manual = "<p>@What do you think of this ?";	$manual.= "<ul><li>a) Yes</li><li>b) No</li><li>c) Okay</li><li>d) Maybe</li></ul>";	$manual.= "</p>";

not equal this;

<p>@What do you think of this ?  <ul>	 <li>a) Yes</li>	 <li>b) No</li>	 <li>c) Okay</li>	 <li>d) Maybe</li>  </ul></p>

are <p> elements really only meant to contain text nodes and not much else ?i think i should switch <p> to <div> to contain the whole set then; because the <p>style doesn't get inherited to the <ul> or <li>s. i have since checked it like so;

<div style="color:red">Circle bullets list:<ul type="circle"> <li>Apples</li> <li>Bananas</li> <li>Lemons</li> <li>Oranges</li></ul>  </div><p style="color:red">Square bullets list:<ul type="square"> <li>Apples</li> <li>Bananas</li> <li>Lemons</li> <li>Oranges</li></ul>  </p>

...Not really sure I understand the question. Are you asking if you can access the <li> elements using getElementsByTagName? Yes, you can access any element.
yes, i was asking that. and yes Ingolme has said you can, but i was not returning the <li> because it seems that a <p> doesn't act like a container as a <div> does.a pity we can't highlight [ code ] markup here - the key point i wanted clarified in my code was this;
	alert(parli.length);	// this is '0' -> no <li> found ?

Link to comment
Share on other sites

The lists aren't inside the <p> elements. Your code looks like this:

<p>@What do you think of this ?  <ul>	 <li>a) Yes</li>	 <li>b) No</li>	 <li>c) Okay</li>	 <li>d) Maybe</li>  </ul></p>

But the browser sees it like this:

<p>@What do you think of this ?</p><ul>   <li>a) Yes</li>   <li>b) No</li>   <li>c) Okay</li>   <li>d) Maybe</li></ul><p></p>

This is because you're not allowed to have lists or other blocks inside paragraphs.

Link to comment
Share on other sites

Just to clarify.Your HTML does not necessarily correspond to the DOM that a browser constructs from it. Same as your house is not built exactly the way the original blue prints said it should be built. When a browser sees incorrect HTML, it does what it can to fix it when it constructs the DOM. The results can be unexpected.One way to debug stuff like this is to use your Firefox DOM Inspector. It will show you the way your document was ACTUALLY constructed by the browser.

Link to comment
Share on other sites

The lists aren't inside the <p> elements. Your code looks like this:
<p>@What do you think of this ?  <ul>	 <li>a) Yes</li>...code...  </ul></p>

But the browser sees it like this:

<p>@What do you think of this ?</p><ul>   <li>a) Yes</li>...code...</ul><p></p>

This is because you're not allowed to have lists or other blocks inside paragraphs.

ahh, okay - that's the key lesson learned here, *thanks*i think i realised that's what you were trying to say, so;Your code isn't putting any lists inside and of your <p> elements."should" have been;Your code is putting lists inside and of your <p> elements *but* the browser does NOT parse it that way.(just to be pedantic... :) )
Just to clarify.Your HTML does not necessarily correspond to the DOM that a browser constructs from it. Same as your house is not built exactly the way the original blue prints said it should be built. When a browser sees incorrect HTML, it does what it can to fix it when it constructs the DOM. The results can be unexpected.One way to debug stuff like this is to use your Firefox DOM Inspector. It will show you the way your document was ACTUALLY constructed by the browser.
is that the same as just "Viewing Source" ?my Firefox is 3.6.18
Link to comment
Share on other sites

Yeah, I forgot that DOM Inspector is an add-on now. It used to be built-in. Fortunately, it's easy to install. I don't know how I'd develop without it.
When was it built-in? It's been an add-on for as long as I've been developing (2.5 - 3 yrs).
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...