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>
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>
Share
Improve this question
asked Oct 23, 2017 at 3:01
New2ProgrammingNew2Programming
451 gold badge2 silver badges9 bronze badges
4
-
Open you browser console. You will see an error like this "Uncaught SyntaxError: Invalid or unexpected token" Which seems to be pointing to this line
(#content.indexOf(text) > -1)
– NewToJS Commented Oct 23, 2017 at 3:04 -
The "text" you are searching for is part of the HTML source, not part of the DIV's text content. Your
text
variable contains a CSS/jQuery style selector, not the actual string you want to search for. – nnnnnn Commented Oct 23, 2017 at 3:07 - are you trying to check if a div contains style="width:550px;" ? – user5525667 Commented Oct 23, 2017 at 3:32
- @TusharTyagi yes – New2Programming Commented Oct 23, 2017 at 6:27
2 Answers
Reset to default 4Here you go with a solution https://jsfiddle/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./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./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