views:

71

answers:

4

I want to get a "p" element which is inside a "td". How can I get it? My code is:

 <td id="mytd"> 
    <p> aaaa </p>
    <p> bbbbb </p>
    <p id="myp"> cccc </p> 
 </td>

I can get the td using. document.getElementById("mytd"), but I don't know how to get the p with id="myp".

Thanks is advance

+7  A: 

Just use exactly the same code getElementById, but use the ID of the <p> instead of the <td>:

var p = document.getElementById("myp");
p.style.background = "#000";
p.style.color= "#FFF";

Here's a jsFiddle showing it working.

GenericTypeTea
I don't know what is wrong, but it didn't get the value of "p" when I am doing this.
novellino
what DOES happen? any errors in the javascript console?
Bobby Jack
@novellino: I think what you want is: `var p = document.getElementById("myp").innerHTML;`
captaintokyo
@novellino - Do you want the content of the p? Or do you want the actual p element from the DOM? Updated my answer as per @captaintokyo's comment.
GenericTypeTea
Actually I want to get the p element in order to change something in the style of it.
novellino
@novellino - It should just be: `var p = document.getElementById("myp");`. So what exactly isn't working? What's the error? I updated my answer and provided a working example for you to look at.
GenericTypeTea
I figured out something else finally, with jQuery for making it work.
novellino
Thanks anyway a lot!
novellino
+2  A: 

document.getElementById("myp")

If you output valid HTML, your IDs you use for DOM elements should be unique for the whole document. Thus, you can do something as simple as this. If this doesn't work (got more elements with this ID), deal with that problem instead. IDs should be unique.

Alexander
Yes the id is unique.
novellino
@Alexander +1 for the right solution
c0mrade
A: 

with jQuery

$("p[id$='myp']")
jatt
a) typo (you're selecting 'a' elements instead of 'p's) b) what's with the 'end of string' selector? c) why do this with an attribute selector anyway (why not just $('#myp') ?) d) asker doesn't mention jQuery e) It's jQuery, not jquery ;-)
Bobby Jack
No it is not jQuery
novellino
:D yep ... my fault ... a->p and discussion about selecting only id and element->id in Jquery is thing that I don't want open here...
jatt
+1  A: 

you could try this jQuery as well :

var p = $("td#mytd p#myp");

Then you can get html or text p.html(); or p.text();

Correction :

I don't think td#anyid(tag name is redundant) is necessary because IDs are unique in document you need those only if you were using classes so I think should do(if you use jQuery that is) :

var p = $("#myp"); 
c0mrade