简体   繁体   中英

Check if text exist in div using jquery

I would like to check if the text exist in the div element, so that if text matches the text in div it will alert "hello". May I know how am I able to achieve this result? Thank you.

  <script type="text/javascript">
    jQuery(document).ready(function(){
        var text = "div[style*=\"width: 550px;\"]";
        if (#content.indexOf(text) > -1){
            alert("Hello");
        }
    });
  </script>
  <div id="content">
    <div style="width:550px;">James</div>
    <div style="width:500px;">Amy</div>
  </div>

Here you go with a solution https://jsfiddle.net/9kLnvyqm/

 if($('#content').text().length > 0) { // Checking the text inside a div // Condition to check the text match if($('#content').text().indexOf('Amy')){ console.log('Hello'); } }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="content"> <div style="width:550px;">James</div> <div style="width:500px;">Amy</div> </div>

If you want only the text content from a container then use text() , if you are looking for html content then use html() .

Hope this will help you.

It is possible to get the value of inline style of an element.

 var wid = $("#content > div")[0].style.width; if(wid === "550px"){ //correct width detected. you can use alert instead of console.log console.log("hello"); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="content"> <div style="width:550px;">James</div> <div style="width:500px;">Amy</div> </div>

You have multiple elements inside #content. you may want to use the return value of

$('#content').children().length;

and loop the program to get inline width of all elements. Ping if you need some help with the loop

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