I am trying to write a simple script in JavaScript, just for testing purposes. I am defining 2 variables, sort of unnecessary, but nice anyway which hold string values for two different scenarios, if the element before the button contains bold text when the button is clicked, the respective variable will be displayed in an alert dialog box.
So, here is my code:
$(document).ready(function(){
var Bold="Yes, some of this text is bold!";
var NoBold="No, none of this text is bold.";
$("<input class="BoldButton" type="button" value="Bold?" id="IntroButton"></input>")
.insertAfter("#intro");
$("<input class="BoldButton" type="button" value="Bold?" id="LatestNewsButton"></input>")
.insertAfter("#news h2");
$("input.BoldButton").click(function(){
if () {
$('').();
} else {
$('').();
{
});
});
I was in the middle of writing my if else statement when I realized I do not know how to check if bold is in the element above the button. I was thinking of using the pseudo-variable this, but I’m pretty sure that’s wrong, because wouldn’t it be the element before the “this” pseudo-variable? I think I may be confusing the purpose of this, sorry about that.
Anyway, I really just need a method of checking to see if the element before the button contains bold text, and then I can do the rest. 🙂
Thanks!
FINAL CODE:
$(document).ready(function(){
var Bold="Yes, some of this text is bold!";
var NoBold="No, none of this text is bold.";
$('<input class="BoldButton" type="button" value="Bold?" id="IntroButton">')
.insertAfter("#intro");
$('<input class="BoldButton" type="button" value="Bold?" id="LatestNewsButton">')
.insertAfter("#news p");
$("input.BoldButton").click(function(){
if ($(this).prev().is(':has(b, strong)')) {
alert(Bold);
} else {
alert(NoBold);
}
});
});
If the text is made bold using
<b>tags, you could use the.is()method with the:has()selector on the previous element to check if it has a any descendant<b>tags.Like this:
The
.is()returns a boolean value if it matches the selector provided. The:has()selector determines if there is a descendant with the selector provided.EDIT: As requested in a comment, updated to include a check for
<strong>tags as well.