Reputation: 15488
I am trying to write a statement along the lines of: 'if given element does not contain the following text, do something'.
I have tried using :contains
as such:
var openingHours = $('.opening-listing:nth-child(' + new Date().getDay() + ')');
if($(openingHours + ':contains("Closed")').length > 0){
//Do something
}
But am getting syntax errors.
Would anyone know what I've done wrong here, or if there is a better way of going about this?
Upvotes: 2
Views: 14512
Reputation: 54
They way I understand your question is that; you have an HTML element with some content (text or number). And you want to use that content in decision making such as if-statement.
Here is an example of the code I made in repl.it, click here.
I give each element a unique id name, so that I can call it in JavaScript for decision-making. Then I add onClick which invokes a function in JavaScript.
<form>
<div>
<input type="text" id="inputName" placeholder="Your name">
</div>
<input type="submit" onClick="getName()" value="Submit">
</form>
Next step is to use document.getElementById(tagName).value which receives the content you have written in the inputfield after you click on submit button. And set the value into a next variable instead of copying the whole line of code. Last but not least, I have also added an example if you have jQuery library, I prefer using jQuery approach because it is less code and easier to understand for beginners.
function getName(){
// Gets the value from HTML and inserts the result in new variable called inputName
var inputName = document.getElementById("inputName").value;
// This works only if you have jQuery library included in html part
//var inputName = $("#inputName").val();
// If-statement
if(inputName === "Peter"){
alert("Name is = " + inputName);
} else if(inputName === "Jacob"){
alert("Name is = " + inputName);
}
}
I hope this gives you different perspective on how to solve your problem. Good luck!
Upvotes: 0
Reputation: 14321
Use the :not()
CSS selector.
var openingHours = $('.opening-listing:nth-child(' + new Date().getDay() + ')');
if($(openingHours).find(':not(:contains("Closed"))').length > 0){
//Do something
}
Upvotes: 2
Reputation: 1
openingHours
is a jQuery object, not a css
selector. You can use .text()
, .indexOf()
, which :contains()
uses internally
if (openingHours.text().indexOf("Closed") === -1) {
// do stuff
}
Upvotes: 5