6

I have some html like this:

<html>
  <body>
    <div>
      <p>Something</p>
    </div>
    <div class="hide" id="show">Protected</div>
  </body>
</html>

I need to display or hide/show an element via JavaScipt if html has "Something" in its text. How can I do that? I need this for my Wordpress page.

4
  • Do you has that some thing in side certain id or class ? Commented Dec 12, 2017 at 11:01
  • Your question title not inline with your description. Title saying search html element but description saying text. What you looking for, the html element which contains the "Something" text or else? Commented Dec 12, 2017 at 11:01
  • 1
    Do you want to search the whole page or specifically target div? Also, please ensure to do some research into how to select an element, how to search it's inner html or text and how to show hide it using JavaScript. Then post the code you have issues with so we can help. - How do I ask a good question - How to create a Minimal, Complete, and Verifiable example - How much research effort is expected of Stack Overflow users before posting a Question? Commented Dec 12, 2017 at 11:02
  • Protected - url to youtube channel. Commented Dec 12, 2017 at 11:02

1 Answer 1

9

Without using jQuery:

var content = document.body.textContent || document.body.innerText;
var hasText = content.indexOf("Something")!==-1;
if (hasText) {
    document.getElementById("show").style.display = 'block';
} else {
    document.getElementById("show").style.display = 'none';
}
Sign up to request clarification or add additional context in comments.

6 Comments

this is exactly what I need. How to run this code after refresh or display a website ? dev.suszek.info/js.html
Do you mean: "How to run javascript code?"? If so: link
Whatever. When I change string "Something" it's dosent work but in fiddle it's works.
Please check dev.suszek.info/js.html IF I change text from something to something2 the js dosent add display: none to html element.
Indeed. That's because you search for 'Something'. Not for 'Something2'
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.