简体   繁体   中英

How can I get a <p> element in a <td>?

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" .

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.

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.

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(); 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"); 

与jQuery

$("p[id$='myp']")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM