Reputation: 129
I'm brand new to JavaScript. I want to know if it's possible to search an HTML page for an element with a known class.
If this is possible how do i do this?
I've got this code:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
var x = document.getElementsByClassName("top_prodname");
</script>
</body>
</html>
Upvotes: 0
Views: 2291
Reputation: 2818
Not sure what you mean about the URL. You can use document.querySelector()
to find DOM elements. Here's an example:
var x = document.querySelector(".top_prodname");
console.log(x);
<span class="top_prodname">example</span>
As @0stone0 commented, you can learn more about querySelector
here.
Using getElementsByClassName()
should work fine, too. You can't create more specific selectors with getElementsByClassName()
like you can with querySelector()
. Although, if getting element references by class name is really all you need, this is fine. Note that it returns an array of element references.
var x = document.getElementsByClassName("top_prodname");
console.log(x[0]);
<span class="top_prodname">example</span>
Upvotes: 3