How to search the DOM for an item with certain class - javascript

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>

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>

Related

I'm trying to get the innerHTML of all <h2> tags and set that as their individual IDs but I'm not sure how to go about it

Basically I have a bunch of <h2> tags and without going into detail, I can't manually assign them IDs. So I THINK I could use .innerhtml to somehow get the <h2> text and assign that as IDs for them but I'm not sure how to get started.
Is this even possible?
The html would look something like this:
<body>
<h2>Science</h2>
<h2>History</h2>
<h2>Mathematics</h2>
<script>
</script>
</body>
As the comments have said, you should avoid using innerHTML unless you are sure you want the HTML content of the element - Using innerText instead will make sure you only receive the plaintext
You can use querySelectorAll to get all of the h2 elements in an HTMLCollection
You can then simply loop over this and update the property directly by using:
ele.id = ele.innerText;
Or you can make use of setAttribute like this:
ele.setAttribute('id', ele.innerText);
.
You might also want to use .toLowerCase() after the innerHTML, just to have a more standard ID styling
document.querySelectorAll('h2').forEach((ele) => {
ele.id = ele.innerText;
});
console.log(document.getElementById('History').innerText);
<body>
<h2>Science</h2>
<h2>History</h2>
<h2>Mathematics</h2>
<script>
</script>
</body>
You will want to use the DOM to find all the h2 elements and process accordingly:
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<h2>Science</h2>
<h2>History</h2>
<h2>Mathematics</h2>
<script>
var h2s = document.querySelectorAll('h2');
h2s.forEach(function(h2Element) {
h2Element.id = h2Element.innerText;
});
</script>
</body>
</html>

document.body.getElementById is not a function

Happy New Year to all. Today, I encountered a very strange thing.
TypeError: document.body.getElementById is not a function
Several times I have checked all the characters, everything must be true
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript">
function addElem()
{
var number=document.body.getElementById("number");
}
</script>
<input type="text" id="number">
<br>
<button onclick="addElem()">Add</button>
</body>
</html>
Why do I get this error?
use document.getElementById() not document.body.getElementById() to achieve the desired effect
That's because document.body is an element. Elements do not have a getElementById() method since ids are unique and using it relative to specific element would be useless.
You cannot have a getElementById() method for the document.body element
Use document.getElementById() instead!

.getElementsByClassName()[] -- what am I not understanding?

I am working with HTML, CSS, jQuery, and JavaScript, all on one HTML page. Generally, I trying to figure out for the first time how to access information from the HTML body for use in my JavaScript code.
I want to set a variable in JavaScript equal to the string contained in the data attribute of one of my <div> elements.
Can I use document.getElementsByClassName()[] in my JavaScript to actually pull the information out of the HTML document? In examples on W3schools and elsewhere, I only see it used to change the value of some HTML element, not to actually use its input. Is there something more fundamental that I'm missing, here?
____here's my more specific code (where div.onlyOne is the only div of that class, and has the data-need attribute "string i need"):
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need")
Why will this not store "string i need" into myVar?
It works, make sure though, that you run the script after the markup or DOM load, or else the script will not find the element as it has not yet been loaded.
After in markup
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<div class="onlyOne" data-need="hey there"></div>
<script type="text/javascript">
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need");
alert(myVar);
</script>
</body>
</html>
DOM load
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need");
alert(myVar);
});
</script>
</head>
<body>
<div class="onlyOne" data-need="hey there"></div>
</body>
</html>
May I suggest you use document.querySelector('.onlyOne') instead in the future. With that you can narrow down the result list in a more efficient way.
Src: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
<div class="onlyOne" data-need="some text">...</div>
var myVar = document.getElementsByClassName("onlyOne")[0].getAttribute("data-need");
alert(myVar);
https://jsfiddle.net/howa6w1o/
since you are using jQuery, you can simplify your code to get the contents of the data-attribute: as follows:
$(document).ready(function(){
var myVar = $(".onlyOne").eq(0).data("need");
})

getElementsByTagName only get top level tags?

i have this really weired js problem.
in summary, i get a element not found if i use (document.getElementsByTagName("p"))[0]
and if the p tag is inside a div like this
<div id="main">
<p>see</p>
</div>
but as soon as i remove the div wrapper, all things work.
after 30 min, i've reduced the problem to this simple code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>ttttttttttttttttttttt</title>
</head>
<body>
<div id="main">
<p>see</p>
</div>
<script type="text/javascript">
var myobj = document.createElement("div");
myobj.innerHTML='yesyes';
document.body.insertBefore(myobj, (document.getElementsByTagName("p"))[0] );
</script>
</body>
</html>
put above in a file. Open in Firefox or Chrome or IE8. If successful, you should see “yesyes”.
If you remove the <div id="main"> wrapper, then it works.
it seems there something i'm not understanding about getElementsByTagName??
Nothing to do with getElementsByTagName, everything to do with insertBefore. Try this:
document.getElementById('main').insertBefore(myobj, (document.getElementsByTagName("p"))[0] );​​
insertBefore needs the parent element. It won't function the way you are calling it (on body), so I just looked up the "main" div instead.
Your problem is with document.body.insertBefore, not with document.getElementsByTagName -- you can see this for yourself by sticking the line
alert(document.getElementsByTagName("p")[0].innerHTML);
at the beginning of the script.
So what's going on with insertBefore? It is a method of all DOM nodes, as you can see at that link, and it will only insert an element (or "document fragment") before one of the direct children of that node. When you have <div id="main> in there, the <p> found by getElementsByTagName is not a direct child of the <body>, so body.insertBefore will not do what you want.
To get the effect you want, use instead
var first_p = document.getElementsByTagName("p")[0];
first_p.parentNode.insertBefore(myobj, first_p);
You have to specify the parent element, not document.body for .insertBefore.
<div id="main"><p>see</p></div>
<script type="text/javascript">
var myobj = document.createElement("div");
myobj.innerHTML='yesyes';
document.getElementById('main').insertBefore(myobj, document.getElementsByTagName("p")[0] );
</script>
you need to append child myobj before inserting it into body
document.body.appendChild(myobj);

Accessing jQuery objects in the module pattern

Really getting in to javascript and looking around at some patterns. One I have come accross is the module pattern. Its seems like a nice way to think of chucks of functionality so I went ahead and tried to implement it with jQuery. I ran in to a snag though. Consider the following code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>index</title>
<script type="text/javascript" charset="utf-8" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var TestClass2 = (function(){
var someDiv;
return {
thisTest: function ()
{
someDiv = document.createElement("div");
$(someDiv).append("#index");
$(someDiv).html("hello");
$(someDiv).addClass("test_class");
}
}
})();
TestClass2.thisTest();
});
</script>
</head>
<body id="index" onload="">
<div id="name">
this is content
</div>
</body>
</html>
The above code alerts the html content of the div and then adds a class. These both use jQuery methods. The problem is that the .html() method works fine however i can not add the class. No errors result and the class does not get added. What is happening here? Why is the class not getting added to the div?
Ah, now that you've updated your question I can better answer your question. You should change the append to appendTo considering you're wanting to move the newly created element inside of the already present #index.
$(document).ready(function() {
var TestClass2 = (function() {
var someDiv = $("#name");
return {
thisTest: function() {
someDiv = document.createElement("div");
$(someDiv)
.html("hello")
.addClass("test_class")
.appendTo("#index");
}
}
})();
TestClass2.thisTest();
});
Hope this helps!
I copied and pasted your code and it works for me.
Make sure you're not simply viewing source to see if the class is applied because doing so simply shows you the HTML that was sent from the server - any DOM updates that occur through JavaScript will not be reflected.
To view the live DOM, use a tool like Firebug or WebKit's Inspector (comes built-in to Safari and Chrome).
Your code works great!
http://jsfiddle.net/lmcculley/p3fDX/

Categories