简体   繁体   English

检查 HTML<p> 标记包含文本,然后更改背景颜色</p>

[英]Check if HTML <p> tag contains text, and then change background color

I need to get help with the question above.我需要就上述问题寻求帮助。

I tried doing:我试着做:

var string = document.getElementById('t')
if(string.includes("ALARM"))
    document.body.style.backgroundColor = "red";

The html tag is html 标签是

Current sensor data: 140 |ALARM 当前传感器数据:140 |ALARM

Thanks for help感谢帮助

var string = document.getElementById('t')

The above line gave you the element with id='t'上面的行给了你id='t'的元素

var string = document.getElementById('t').innerText;

The above line will give you the inner text of that HTML element上面的行将为您提供该 HTML 元素的内部文本

You will have to make this one change你将不得不做出这一改变

If all you are doing is checking for the presence of ANY text in the element - then you can use the :empty pseudo-selector ....如果您所做的只是检查元素中是否存在任何文本 - 那么您可以使用:empty pseudo-selector ....

If you are checking for the presence of specific text in the element - then you will need the javascript solutions provided by the other solutions.如果您正在检查元素中是否存在特定文本 - 那么您将需要其他解决方案提供的 javascript 解决方案。

However in the interest of a css solution - the:empty selector is a CSS selector that triggers when the element is empty (or contains only a comment) - note that whitespace DOES count as content so its not a perfect option....然而,为了 css 解决方案的利益 - the:empty 选择器是一个 CSS 选择器,当元素为空(或仅包含注释)时触发 - 请注意,空格确实算作内容,因此它不是一个完美的选择......

The second and third p elements are empty - even though the third has a comment第二个和第三个 p 元素是空的 - 即使第三个有注释

 p { height: 16px; } p:empty { border:solid 1px red }
 <p>I have content</p> <p></p> <p><!-- I do not have content--></p> <p>I have content</p>

If you want the p with the content to be highlighted - then you can use the :not selector in combination with the :empty selector;如果您希望突出显示内容的 p - 那么您可以将:not选择器与:empty选择器结合使用;

 p { height: 20px; } p:empty { border: dashed 1px lightgrey; } p:not(:empty) { background: yellow; border: solid 1px red; color:red; font-weight: bold; line-height: 20px; padding: 8px; }
 <p></p> <p>ALARM</p> <p></p>

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

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