简体   繁体   English

我如何获得 <p> 元素 <td> ?

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

I want to get a "p" element which is inside a "td". 我想在“ td”中获取一个“ p”元素。 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. 我可以使用td。 document.getElementById("mytd") , but I don't know how to get the p with id="myp" . document.getElementById("mytd") ,但我不知道如何使用id="myp"获得p。

Just use exactly the same code getElementById , but use the ID of the <p> instead of the <td> : 只需使用完全相同的代码getElementById ,但使用<p>的ID而不是<td>

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

Here's a jsFiddle showing it working. 这是一个显示其工作原理的jsFiddle。

document.getElementById("myp")

If you output valid HTML, your IDs you use for DOM elements should be unique for the whole document. 如果输出有效的HTML,则用于DOM元素的ID在整个文档中应该是唯一的。 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. 如果这不起作用(使用此ID获取更多元素),请改为处理该问题。 IDs should be unique. ID应该是唯一的。

you could try this jQuery as well : 您也可以尝试使用此jQuery:

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

Then you can get html or text p.html(); or p.text(); 然后您可以获取html或文本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) : 我认为td#anyid (标记名称是多余的)不是必需的,因为ID在文档中是唯一的,只有在使用类时才需要ID,所以我认为应该这样做(如果使用jQuery):

var p = $("#myp"); 

与jQuery

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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