In this way, I was trying to select the a tag but it has not been selected so please help me select
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
(function($) {
var test = $('.page_item').find('> a').text();
alert(test);
})(jQuery)
</script>
</head>
<body>
<li >
<a href="http://localhost/techblog/contac-us/">Contac us</a>
</li>
</body>
</html>
CodePudding user response:
Why not just add this to the selector, istead of using find?
$('.page_item > a').text()
Also it would be as following with find method:
$('.page_item').find('a').text();
CodePudding user response:
Just make it easier for yourself by adding an ID to the a
element:
<a id="js-contact-us" href="http://localhost/techblog/contac-us/">Contac us</a>
Then:
$('#js-contact-us').text()
EDIT
Note: Your code as written WORKS. (However inelegant it might be.)
Are you sure it's only executing once the DOM is ready (the HTML has been parsed?). If you run it as it is in your example, the script will run before the HTML is loaded.
Move the script tag to before the closing body tag, or add defer
, or wrap it in the DOMContentLoaded
:
document.addEventListener('DOMContentLoaded', () => {
$('#js-contact-us').text()
});
CodePudding user response:
the script should be after elements , your html should look like this :
<!DOCTYPE html>
<html>
<head>
<!-- meta tags and title -->
</head>
<body>
<li >
<a href="http://localhost/techblog/contac-us/">Contac us</a>
</li>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
(function($) {
var test = $('.page_item > a').text();
alert(test);
})(jQuery)
</script>
</body>
</html>